double bonusScore = 10;
if (bonusScore > 0) {
//code body
}
I want to compare bonusScore which is double with 0, how should i do, because if done in above way it is not accurate and I do not know why.
double bonusScore = 10;
if (bonusScore > 0) {
//code body
}
I want to compare bonusScore which is double with 0, how should i do, because if done in above way it is not accurate and I do not know why.
In java, we need to be careful when comparing floating point number. Example:
double a = 1.3;
double b = 3.0;
double bonusScore = a * b;
System.out.println(bonusScore); // expect bonusScore = 3.9
bonusScore = bonusScore - 3.9;
System.out.println(bonusScore); // expect bonusScore = 0
I have ouput:
3.9000000000000004 // expect 3.9
4.440892098500626E-16 // expect 0
So clearly, we have to compare them with the allowed tolerance. Here we need compare bonusScore
to zero with tolerance 0.00001
:
if (bonusScore > 0.00001)
I have read a very useful article about floating point number. Hope this help.
Define an epsilon that is very close to zero. Then you get max( bonusScore, epsilon ). if this max returns the value of epsilon, bonusscore is very close to zero. keep in mind to remove any signs from your bonusScore.
For non exact comparasion:
You need to know your epsilon (measure of equality) and compare double like that:
public static boolean equals(double x, double y, double epsilon){
return Math.abs(x-y) < epsilon;
}
For exact comparasion Try something in lower level:
public static boolean equals(double x, double y) {
return Double.doubleToLongBits(x) == Double.doubleToLongBits(y);
}
Be careful with exact comparasions on double.