drunkmonkey
drunkmonkey

Reputation: 1181

Nan from maths equation

Hi I have the following equation in a piece of java code:

double z = 0.002378 * (Math.pow((1 - (Math.pow(6.875, -6) * y)), 4.2561));

when I set y to be very large values, i.e 200000 I get Nan (Not a number) It's working okay at slightly lower values, 130000

Can anyone tell me why that is?

Additionally I've tried to port the above code from an original BASIC program:

.002378*(1-(6.875*10^-6*ALT))^4.2561

I may have done it wrong? The order of operations isn't very explicit in the BASIC code

Thanks

Upvotes: 0

Views: 926

Answers (3)

ruakh
ruakh

Reputation: 183251

As the Javadoc for Math.pow explains:

If the first argument is finite and less than zero [… and] the second argument is finite and not an integer, then the result is NaN.

So whenever your y is great enough that 1 - (Math.pow(6.875, -6) * y is negative, you'll get NaN.

(This makes sense when you consider the underlying math. A negative number to a non-integer power is not a real number, and double has no way to represent complex numbers.)


Edited for updated question:

Your Basic code has 6.875*10^-6 (meaning 6.875 × 10−6), but your Java code has Math.pow(6.875, -6) (meaning 6.875−6), which is a somewhat greater value, so your Java code triggers this problem for somewhat smaller values of y. This may be why you're seeing this problem now. To match the Basic code, you should change Math.pow(6.875, -6) to 6.875e-6.

Upvotes: 3

andy
andy

Reputation: 1356

Negtive number with real number power may get NAN

Upvotes: 0

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

Raising a negative number to a non-integer power results in an imaginary number in complex number mathematics, a NaN in Java arithmetic. If you really need to do that calculation, you need a complex number package. However, it is more likely that there is an error in your equation or you are trying to use it outside its range of validity.

Upvotes: 0

Related Questions