-1

Sorry if this has been asked before but I was very unsure how to formulate my search to get any relevant results.

Basically I have a class "Wheel", and within that class I am declaring how the == operator should work:

    bool operator == (Wheel& anotherWheel){
    //Circumference of a wheel, times its RPM should give its speed
    //The speed will be in what ever unit the radius is, per minute
    double ourSpeed = 2 * PI * radius * rpm; 
    double anotherSpeed = 2 * PI * anotherWheel.getRadius() * anotherWheel.getRpm();

    cout << ourSpeed << " vs " << anotherSpeed << endl;
    if (ourSpeed == anotherSpeed){
        return true;
    }

    return false;

This works except for when the radius and RPM of a wheel are the same as the others, except switched. So in other words it does not return true for:

2*PI*3*10 vs 2*PI*10*3

Even though I print it out and they are the exact same in the console (as they should be unless my basic math knowledge is completely out of whack).

I managed to solve it by adding a paranthesis when calculating the speeds:

        double ourSpeed = 2 * PI * (radius * rpm); 
        double anotherSpeed = 2 * PI * (anotherWheel.getRadius() * anotherWheel.getRpm());

But I want to understand why this happens, PI is just a constant double I declared so that shouldn't matter.

Thanks!

Okee
  • 23
  • 5
  • 1
    https://stackoverflow.com/questions/18971533/c-comparison-of-two-double-values-not-working-properly – agent_bean Feb 01 '18 at 11:12
  • If you think two `double`s `a` and `b` are the same then try `a - b`. I wouldn't wonder if you get a tiny number instead of 0 (as expected). – Scheff's Cat Feb 01 '18 at 11:14
  • The above experiment suggests a simple solution: `if (fabs(a - b) < eps)` where `eps` defines a tolerated error (i.e. an "epsilon environment"). I don't like `eps` but due to the nature of floating point this is sometimes the only simple solution. – Scheff's Cat Feb 01 '18 at 11:16

1 Answers1

1

Be careful with floating point numbers.

The addition of a set of floating point numbers can vary, according to the order in which you add them. The same is true for multiplication, and various other operations.

This is because of the rounding that occurs due to precision limits.

e.g. 1/3 + 1/3 = 2/3

however

0.33333334 + 0.33333334 = 0.6666668 not 0.6666667, which is what 2/3 would ideally be.

You will need to use a tolerance level, to determine if the value is 'close enough' to considered equal.

A very basic (naive and inflexible) option would be something like:

if(fabs(a - b) < 0.001)

But there are better ways.

If you really want to understand floating point numbers, start here: Oracle Floating Point - it will tell you everything you need to know, and more besides.

Rags
  • 311
  • 1
  • 7