Question

I'm trying to find possible integer roots of a quadratic equation with Java.

enter image description here

Here is a snippet from my code:

double sqrtDiscriminant = Math.sqrt(b * b - 4 * a * c);

double  root1 = ((-1.0 * b) - sqrtDiscriminant) / (2.0 * a);
double  root2 = ((-1.0 * b) + sqrtDiscriminant) / (2.0 * a);

For a = 2, b = -1 and c = -40755, one of the roots is 143.0 (143.0 is printed to console when I echo it so I'm only interested in such double values, not 143.00001) My question is, how can I make sure that any root has an integer value? If root1 = 143.0 then e.g. root1 == 143 should return true.

I tried root1 == Math.floor(root1) but it didn't work.

Was it helpful?

Solution 2

If I would be you, I will simply take the int/long value of the roots and re-verify the equation to make sure that int/long value of the root is OK or not e.g.

// using round because an equivalent int/long may be represented by a near binary fraction
// as floating point calculations aren't exact
// e.g. 3.999999.. for 4
long longRoot = Math.round(root1); 
if(a*longRoot*longRoot +  b*longRoot + c==0){
    //its valid int root
}else{
    //ignore it
}

OTHER TIPS

You should never use equality checks when working with double-values. Define an accuracy value like

double epsilon = 0.0000001;

Then check whether the difference is nearly equal to epsilon:

if(Math.abs(Math.floor(value)-value) <= epsilon) { }

You can test the integer value if it's a solution also:

x = Math.floor(root1);
if(a*x*x+b*x+c == 0)
...

If you want an integer result use round as your error might mean the number is slightly too large or slightly too small.

long l = Math.round(value);

To round to a fixed number of decimal places you can use

double d = Math.round(value * 1e6) / 1e6; // six decimal places.

You can try as

Math.rint(d) == d
if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
    // int
}

If variable is equal to the Math.floor then its Integer. The infinite check is because its will not work for it.

the best way will be check whether (Math.floor(root1)-root1)<=0.0000001 It will give you the correct output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top