[英]MATLAB angle() to C# conversion
I want to transfer to C#, a function that computes the phasor angle of an expression from MATLAB, angle()
. 我想转移到C#,这是一个从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 . 我发现
angle(x+yi)=atan2(y,x)
但是这里出现了我的问题,我有一个平方根 ,根据我给它的值是正数还是负数 。 But, in MATLAB if the sqrt function gets a negative, it returns an imaginary , unlike C# where it returns NaN . 但是,在MATLAB中,如果sqrt函数得到负数,它将返回一个虚数 ,与C#不同,它返回NaN 。
So, how can I make the two codes give the same result? 那么,我怎样才能使两个代码给出相同的结果呢?
ie MATLAB: 即MATLAB:
angle(a*1i-sqrt(expression))
C#: C#:
Mathf.Atan2(a,-sqrt(expression))
(what i do, and i think is wrong) Mathf.Atan2(a,-sqrt(expression))
(我做什么,我认为是错的)
You could do the same thing Matlab does and use Complex math: 你可以做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;
}
}
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: 如果您不想这样做,您可以看到,如果
expression
为负,则sqrt(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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.