Блог пользователя rahul_1234

Автор rahul_1234, история, 9 лет назад, По-английски

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.

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

»
9 лет назад, # |
Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

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

  • »
    »
    9 лет назад, # ^ |
    Rev. 3   Проголосовать: нравится +1 Проголосовать: не нравится

    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 лет назад, # ^ |
      Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

      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 лет назад, # ^ |
        Rev. 4   Проголосовать: нравится +1 Проголосовать: не нравится

        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 лет назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

Can anybody help me on this?