Question

I have a litle problem in my new Java programm. I want to calculate the turning point of f`(x)= gx^2+hx^2+i with the pq-formula but the only result I get is "NaN"...

This is the code where the error must be:

m = g/g;  // I had already worked with the variables
n = h/g;  // I am working with double
o = i/g;

p = -(n/2)+ Math.sqrt((n/2)*(n/2) -o);  // pq-formula

String z = String.valueOf(p);

jLabel3.setText(z);

Sorry for my bad english I am from Germany :) Thanks for your help!

Était-ce utile?

La solution

Lets take some time and see what operators here could return a NaN

m = g/g; n = h/g; o = i/g;

As long as g, h, and i are actual numbers, m, n, and o will be actual numbers too.

Math.sqrt((n/2)*(n/2) -o)

From the Math#sqrt(double) javadoc page:

" Returns: the positive square root of a. If the argument is NaN or less than zero, the result is NaN."

So your problem is probably in the fact that (n/2)*(n/2) -o is a negative number after calculating.

(n/2)*(n/2): No matter whether n is positive Or negative, this will always be positive, so...

-o You are subtracting o here, so the most likely problem here is that o is greater that (n/2*(n/2), hence making the calculation negative and Math#sqrt(double) returns a NaN.

TL;DR

Make sure o is smaller than (n/2)*(n/2), otherwise Math.sqrt((n/2)*(n/2) -o) will return a NaN.

Autres conseils

An NaN will be returned if you give Math.sqrt() a negative number. You should include a check to make sure that o <= (n/2)*(n/2).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top