In C++, for comparing doubles we do:
bool AreSame(double a, double b) { return fabs(a — b) < epsilon; } // epsilon : 0.000000001
However in java to compare Bigdecimal properly would this suffice:
if(r.compareTo(BigDecimal.ZERO) == 0) { System.out.print("Yes"); }
Or we have to do something else. Can somebody elaborate on this.
Your code will output "Yes" if r is equal to 0, and nothing if r is not equal to 0
I am asking that sometimes there are errors while comparing double. So we have to use the code in c++ which I specified. However if there is error while comparing two Bigdecimal, compareTo function can detect it properly or we have to use epsilon like thing in java.
I am not asking for output but asking that is there any precision error using compareTo. If there is then how to remove it.
Just as always — Compare abs of difference to epsilon.
compareTo
works perfectly if the values are equal (even with different scale). So if you need to compare with precision — use eps.U r saying that compareTo works perfectly if the values are equal (even with different scale).
Why would I need to: Compare abs of difference to epsilon.
What I am saying is for double too we have Double.compare(d1, d2), so what's the need of epsilon. I just want to confirm that these inbuilt compare functions work perfectly without any error.
Can anybody help me on this?