0

Possible Duplicate:
Why can't decimal numbers be represented exactly in binary?

I have a problem,am solving a simplex problem,while several iterations,in 1 iteration the value turned out to be .400000,now i am multiplying this value with 100 to obtain 40.000000.Now am subtracting this value with 40,but the solution is coming out to be .000001.Please help me out with this,am not able to figure out how this value is turning out to .000001?? As this .000001 is giving problems while checking value,i.e i am comparing with 0,but compiler is treating this as value greater than 0,and am getting wrong answer.How can i correct this error?

Community
  • 1
  • 1
Nimesh
  • 1
  • 1
  • *sigh* Floating point precision (http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems) - if there'd be some SO FAQ, this would be one of the top 10. – schnaader Apr 30 '11 at 20:52
  • so is there any solution to this problem? – Nimesh Apr 30 '11 at 20:57
  • @Nimesh: don't use `float` variables; use `double` instead – pmg Apr 30 '11 at 21:05
  • @pmg Nice, now I also know! So the concept is - the more space in memory the more precisely you can represent the number? – rzetterberg Apr 30 '11 at 21:07
  • while using double ,its showing abnormal program termination..!! – Nimesh Apr 30 '11 at 21:35
  • @Nimesh: don't use `==` with `double` (or `float`); use `<= VERY_SMALL_VALUE` instead, as eg `if (delta <= 0.00001) break;`. Pay attention to negative values; maybe use `fabs()` before the comparison ... `if (fabs(delta) <= 0.00001)` – pmg Apr 30 '11 at 21:44
  • 1
    @Ancide: I implemented [Madhava's method for calculatin pi](http://en.wikipedia.org/wiki/Pi#Second_millennium_AD) in `float`, `double`, and (C99) `long double` and [tested it on ideone](http://ideone.com/68h18). Apparently `float` has 8 digits precision; `double` has 16; and `long double` has 19 digits of precision. – pmg Apr 30 '11 at 22:09

1 Answers1

2

It has to do with the machine precision in Floating points. Have a read about it here: http://en.wikipedia.org/wiki/Floating_point#Machine_precision

rzetterberg
  • 10,146
  • 4
  • 44
  • 54
  • so is there any solution to this problem? – Nimesh Apr 30 '11 at 21:01
  • I'm afraid that is above my knowledge. But have a read http://en.wikipedia.org/wiki/Floating_point#Minimizing_the_effect_of_accuracy_problems and see if you get any viser :) – rzetterberg Apr 30 '11 at 21:05