I want to transfer to C#, a function that computes the phasor angle of an expression from MATLAB, angle()
. I found that angle(x+yi)=atan2(y,x)
but here comes my problem, I have a square root that depending on the values I give it is either positive or negative. But, in MATLAB if the sqrt function gets a negative, it returns an imaginary, unlike C# where it returns NaN.
So, how can I make the two codes give the same result?
ie MATLAB:
angle(a*1i-sqrt(expression))
C#:
Mathf.Atan2(a,-sqrt(expression))
(what i do, and i think is wrong)
You could do the same thing Matlab does and use Complex math:
using System.Numerics;
public static class Foo
{
public static double GetAngle(double a, double expression)
{
Complex cA = new Complex(0, a);
Complex sqrt = Complex.Sqrt(expression);
Complex result = cA - sqrt;
return result.Phase;
}
}
If you don't want to do that, you can see, that sqrt(expression)
is a number on the (positive) imaginary axis if expression
is negative meaning that a*i-sqrt(Expression) == (a-sqrt(abs(expression)))*i
the phase of which is either pi/2 or 3*pi/2:
public static class Foo
{
public static double GetAngle(double a, double expression)
{
if (expression < 0.0)
{
double result = a - Math.Sqrt(-expression);
if (result > 0.0)
return Math.PI * 0.5;
else if (result < 0.0)
return Math.PI * 1.5;
else
return 0.0;
}
else
return Math.Atan2(a, -Math.Sqrt(expression));
}
}