rahul_1234's blog

By rahul_1234, history, 9 years ago, In English

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.

  • Vote: I like it
  • +1
  • Vote: I do not like it

»
9 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

Your code will output "Yes" if r is equal to 0, and nothing if r is not equal to 0

  • »
    »
    9 years ago, # ^ |
    Rev. 3   Vote: I like it +1 Vote: I do not like it

    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.

    • »
      »
      »
      9 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      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.

      • »
        »
        »
        »
        9 years ago, # ^ |
        Rev. 4   Vote: I like it +1 Vote: I do not like it

        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.

»
9 years ago, # |
  Vote: I like it +1 Vote: I do not like it

Can anybody help me on this?