1
votes

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)

1
help me with the title somebodyhey
Take absolute value of expression. Remember from junior high school CAST. Cosine is positive in 4th quadrant, all functions positive in 1st quadrant, Sine positive in 2nd quadrant, Tangent positive in 3rd quadrant.jdweng
@jdweng i think that wont do, in matlab the sqrt(negatives) are giving an imaginary number which are used to the calculations, by using abs value i am changing the result such that c# wont behave as matlabhey
There is really no difference between ax+by and ax+bi as long as you realize the i axis is sqrt -1. The math is the same.jdweng
@jdweng Well, i do not fully understand what you are trying to tell me, but for testing I moved sqrt(expression) while expression has a negative value which means sqrt returns an imaginary, so that c# corresponds to: Mathf.Atan2(a-sqrt(abs(expression)),0)(whose result is pi/2 always) and the result for matlab was the same for the same input, so i guess sqrt in c# should change parameter position depending of the sign of the expression, maybe with a simple if statement. I did what you told me which I understand as : Mathf.Atan2(a,-sqrt(abs(expression))) and did not yield same results.hey

1 Answers

0
votes

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