Reputation: 25950
I'm trying to find possible integer roots of a quadratic equation with Java.
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.
Upvotes: 2
Views: 1066
Reputation: 34367
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
}
Upvotes: 2
Reputation: 3735
the best way will be check whether (Math.floor(root1)-root1)<=0.0000001
It will give you the correct output.
Upvotes: 0
Reputation: 47978
You can test the integer value if it's a solution also:
x = Math.floor(root1);
if(a*x*x+b*x+c == 0)
...
Upvotes: 2
Reputation: 533482
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.
Upvotes: 1
Reputation: 627
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.
Upvotes: 0
Reputation: 9365
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) { }
Upvotes: 3