hey - 1 year ago 119

C# Question

I want to transfer to C#, a function that computes the phasor angle of an expression from MATLAB,

`angle()`

`angle(x+yi)=atan2(y,x)`

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))`

Answer Source

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));
}
}
```