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. How to solve it? Why 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...
After closer examination, as you're not actually modifying x
at any point, it really depends on the incoming value of x
. If it's a finite value greater than or equal to 2, it should be fine. But if x
is smaller than 2, it will fail (well, return NaN) for reasons of simple maths...
You can see there all 3 cases when Math.Pow returns NaN:
http://msdn.microsoft.com/en-us/library/system.math.pow.aspx
public static double Pow(double x, double y)
1) x or y = NaN.
2) x < 0 but not NegativeInfinity; y is not an integer, NegativeInfinity, or PositiveInfinity.
3) x = -1; y = NegativeInfinity or PositiveInfinity.
Math.Pow is not defined for numbers less than 0 for given power. So you function will fail for some x.
x < 0 but not NegativeInfinity; y is not an integer, NegativeInfinity, or PositiveInfinity.
Result: NaN
If you look here it explains all the situations where Math.Pow will give NaN. I suspect this case may be your problem:
x < 0 but not NegativeInfinity; y is not an integer, NegativeInfinity, or PositiveInfinity.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.