1

I can't understand why the statements are giving different results as According to Me a==b is same as b==a

#include<iostream>
#include<cmath>
using namespace std;
int main()
{  
   cout<<(pow(10,2)==(pow(8,2)+pow(6,2)))<<endl;
   cout<<((pow(8,2)+pow(6,2))==pow(10,2))<<endl;
   return 0;
}

OUTPUT IS-

1
0
  • 5
    Floating precision... – Jarod42 Nov 02 '21 at 10:24
  • 3
    comparing floats with `==` is always a bad idea – Raildex Nov 02 '21 at 10:26
  • do not use `pow` for integer types! – Marek R Nov 02 '21 at 10:28
  • 2
    Cannot [reproduce](https://godbolt.org/z/5GKoTcPTz), BTW. What compiler/version/standard are you using? – Bob__ Nov 02 '21 at 10:31
  • 1
    anyway I wonder which compiler gives this result. Outcome should be same even for floating point lack of precision. Gcc gives `1` twice: https://godbolt.org/z/T6j3dz7aK – Marek R Nov 02 '21 at 10:31
  • An implementation of `pow` that doesn't return the best possible `double` for integral arguments ought to be considered defective. Of course neither the C++ nor IEEE754 mandates that (cf. `sqrt` where IEEE754 does). A good toolchain ought to give you the result you expect. You might get better results with `std::pow` which has overloads for integral types. – Bathsheba Nov 02 '21 at 10:40
  • I can recreate the behaviour with gcc-6.3.0 that ships with mingw32 – Peter Nov 02 '21 at 10:51
  • Just out of curiosity, what's the output you get from this [snippet](https://godbolt.org/z/1o8c41YKh)? – Bob__ Nov 02 '21 at 10:59

1 Answers1

0

This is double comparison issue. You can use something like:

   cout<<(fabs(pow(10,2) - (pow(8,2)+pow(6,2))) <  std::numeric_limits<double>::epsilon() ) <<endl;
   cout<<(fabs((pow(8,2)+pow(6,2))-pow(10,2)) <  std::numeric_limits<double>::epsilon() ) <<endl;

Ref: What is the most effective way for float and double comparison?

artm
  • 17,291
  • 6
  • 38
  • 54