MATLAB: Phase shift – different results with pi/2 and 1.570796326

simulink

Hello, I have simple Simulink project that calculates phase shift from two sine waves: https://i.imgur.com/fgI62xQ.png
If I set phase of one signal as pi/2 rad (the other one's phase = 0) the result is following: https://i.imgur.com/QjioJE8.png
But setting phase as 1.5707963268 (which equals to pi/2) results in correct diagram:https://i.imgur.com/MTc3l9K.png
Why is this happening?

Best Answer

Hi Buli,
Although I don't have simulink, I think it is reasonably clear what is going on. I will assume here that -pi/2 is the desired answer as in the second plot. You are taking atan(a/b) of two quantities, where 'a' is very close to 1 and b is very close to zero. When you use pi/2 as the phase, this drives b very close to zero, coming in from the negative side. But because of numerical issues b can come out on either side of zero. Then
atan(1/-eps)
ans = -1.5708
atan(1/eps)
ans = 1.5708
so things bounce around between +-pi/2 (approximately). On the other hand, a phase of 1.5707963268 is definitely not equal to pi/2:
1.5707963268 - pi/2
ans = 5.1035e-12
and that extra bit of numerical cushion means that b does not get pushed on the wrong side of zero.
If the answer was actually supposed to be +pi/2, then it's likely that a similar argument can show that the 5e-12 is always keeping b on the (reassesed) wrong side of zero.
I don't know if simulink has the atan2 function, but if so this whole problem can be made to go away.