首页 文章

MATLAB angle()到C#的转换

提问于
浏览
1

我想转移到C#,这是一个计算MATLAB, angle() 表达式的相量角的函数 . 我找到 angle(x+yi)=atan2(y,x) 但是这里出现了我的问题,我有一个平方根,根据我给它的值是 positivenegative . 但是,在MATLAB中,如果sqrt函数变为负数,则返回 imaginary ,与C#不同,它返回 NaN .

那么,我怎样才能使两个代码给出相同的结果呢?

即MATLAB:

angle(a*1i-sqrt(expression))

C#:

Mathf.Atan2(a,-sqrt(expression)) (我做了什么,我认为是错的)

1 回答

  • 0

    你可以做Matlab做的同样的事情,并使用复杂的数学:

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

    如果您不想这样做,您可以看到 sqrt(expression) 是(正)虚轴上的数字,如果 expression 为负,意味着 a*i-sqrt(Expression) == (a-sqrt(abs(expression)))*i 其相位为pi / 2或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));
        }
    }
    

相关问题