Search code examples
javamathintegerdoubledouble-precision

How to determine whether a double variable has integer value?


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.


Solution

  • 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
    }