简体   繁体   English

C#Math.pow(x,0.333)

[英]C# Math.pow(x, 0.333)

private double f(double x, double zn = 1)
    {
        double X = - zn;
        X *= x * x * (x + 1);
        X *= Math.Pow((x - 2), 0.333);
        return funct ? x : X;
    }

I have this code. 我有这个代码。 When I try to find Math.Pow((x-2), 0.333) - i have NaN. 当我尝试找到Math.Pow((x-2),0.333)-我有NaN。 How to solve it? 怎么解决呢? Why NaN? 为什么是NaN?

Rewritten... 改写...

private double f(double x, double zn = 1)
    {
        double answer = - zn;
        answer *= x * x * (x + 1);
        answer *= Math.Pow((x - 2), 0.333);
        return answer;
    }

My guess is that you're taking the cube root of a negative number. 我的猜测是您要使用负数的立方根。 That seems the most likely cause, but your code is really hard to read due to having both x and X as local variables... 这似乎是最可能的原因,但是由于xX作为局部变量,因此您的代码确实很难阅读...

After closer examination, as you're not actually modifying x at any point, it really depends on the incoming value of x . 经过仔细检查,由于您实际上并没有在任何时候修改x ,因此实际上取决于x的传入值。 If it's a finite value greater than or equal to 2, it should be fine. 如果它是一个大于或等于2的有限值,那应该没问题。 But if x is smaller than 2, it will fail (well, return NaN) for reasons of simple maths... 但是如果x小于2,由于简单的数学原因,它将失败(返回NaN)。

You can see there all 3 cases when Math.Pow returns NaN: 您可以看到Math.Pow返回NaN的所有3种情况:

http://msdn.microsoft.com/en-us/library/system.math.pow.aspx http://msdn.microsoft.com/zh-CN/library/system.math.pow.aspx

public static double Pow(double x, double y) 公共静态double战俘(double x,double y)

1) x or y = NaN. 1)x或y = NaN。

2) x < 0 but not NegativeInfinity; 2)x <0,但不是NegativeInfinity; y is not an integer, NegativeInfinity, or PositiveInfinity. y不是整数,NegativeInfinity或PositiveInfinity。

3) x = -1; 3)x = -1; y = NegativeInfinity or PositiveInfinity. y = NegativeInfinity或PositiveInfinity。

Math.Pow is not defined for numbers less than 0 for given power. 对于给定功率,未为Math.Pow定义小于0的数字。 So you function will fail for some x. 因此,您的功能将因x失败。

x < 0 but not NegativeInfinity; x <0,但不是NegativeInfinity; y is not an integer, NegativeInfinity, or PositiveInfinity. y不是整数,NegativeInfinity或PositiveInfinity。
Result: NaN 结果:NaN

If you look here it explains all the situations where Math.Pow will give NaN. 如果您在此处查看它将说明Math.Pow将提供NaN的所有情况。 I suspect this case may be your problem: 我怀疑这种情况可能是您的问题:

x < 0 but not NegativeInfinity; y is not an integer, NegativeInfinity, or PositiveInfinity.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM