0

I'm writing a function which accepts a double data type, say variable 't', and if 't' is equal to 0.05, the function does something.

Now, my problem is that if 't' is 100-99.5, the function fails to work. But it works for 't' = 0.05-0. I'm guessing this is something to do with how numbers are stored. What's the work around?

PS : I'm not a programmer, merely using C++ as a tool, so I don't know much about it other than the basics. A simple solution would be very appreciated.

user3073511
  • 101
  • 1
  • 7
  • You can compare that the number is close enough to `0.5`, where you get to define "close enough". – juanchopanza Dec 06 '13 at 07:45
  • 1
    **100-99.5 ~ 0.5**, and **100-99.95 ~ 0.05**? – Deidrei Dec 06 '13 at 07:47
  • 1
    Floating point arithmetic is inaccurate, this is true in any language I know. The simple solution is not to use floating point arithmetic when exact accuracy is required. For instance programs that are counting money should count in cents/pennies, not dollars/pounds. – john Dec 06 '13 at 07:47
  • 3
    that's because 100 - 99.5 = 0.5 not 0.05 – Lenny Dec 06 '13 at 07:49
  • @Lenny I'm guessing that's a typo in the question, otherwise we're all answering the wrong question. – john Dec 06 '13 at 07:50
  • @john well since he specified it's a double it shouldn't be a floating point error with only 2 decimal places and basic subtraction. Simplest solution... right? – Lenny Dec 06 '13 at 07:54
  • 1
    @Lenny There are floating point errors even in simple subtraction. 100.0 - 99.95 == 0.05 is not guaranteed to be true in floating point arithmetic. In general neither 99.95 or 0.05 have exact representations as floating point numbers. So expecting arithmetic involving those numbers to give exact results is wrong. – john Dec 06 '13 at 07:58
  • You have to tell us why you are doing this. Otherwise we can't tell you how to work around it. Probably there is a perfectly robust solution that doesn't rely on arbitrary error tolerances, but we need to know more. – TonyK Dec 06 '13 at 08:14
  • Apologies, as pointed out, it is 100-99.95 in the original question. As to why I am doing this, I'm writing a program to simulate a mass on a pendulum using the Leap Frog method. Basically, I calculate the position using a function x(t), where t is a variable which increments by 0.1 for each iteration. To calculate x(t), I use the formula x(t) = x(t-0.1) + 0.1*(v(t-0.05)). Further, v(t) = v(t-0.1) + 0.1*a(t-0.05), and a(t) = -x(t). v = velocity, a = acceleration. x(0) is accepted by the user. – user3073511 Dec 06 '13 at 08:50

1 Answers1

1

In c++ or any language == operator is not recommended for double or float type because the variable stores approx value not the exact value with very slight error. Lets say you are using double variable t to compare equality with 0.05 you can use the following code:

if( t-0.00000000001<=0.05 && t+0.00000000001>=0.05 )

It will work fine in this case

kamleshi9
  • 63
  • 1
  • 6