0

How do people deal with floating point inaccuracy in ANSI C? In this case, there is an expected result of 4.305, but ANSI C returns an additional 0.000001?

#include<stdio.h>
main()
{
  float _lcl1=66.3;
  float _ucl1=76;
  float lbl1 = 0;
  float ubl1 = 0;
  lbl1 = (_lcl1 - 2.5 * (_ucl1 - _lcl1));
  printf ("%e\n",lbl1);
}

4.205001e+01

Ideas I have are that this must be a common issue so there is a standard lib to deal with this or people convert these to integers, do the calculation, and then convert them back? Can someone provide some insight on a successful "in practice" strategy?

3
  • 4
  • I am wondering how many times we will see floating point questions here
    – Coren
    Feb 27, 2012 at 18:00
  • People deal with this by using decimal arithmetic rather than binary floating point. That's not built in to C so you would need a library. Simply put, binary floating point is not designed to do what you desire. Feb 27, 2012 at 22:16

1 Answer 1

7

This has nothing to do with ANSI C and everything to do with floating point arithmetic.

You should read: "What Every Computer Scientist Should Know About Floating-Point Arithmetic" http://www.math.umd.edu/~jkolesar/mait613/floating_point_math.pdf

To give an inadequate summary, floating point arithmetic is not a magic infinite precision mechanism -- it is an approximate way of representing an infinite set of real numbers using a small (typically 32 or 64) number of bits. It does its work in binary, not in decimal, and the fractions exactly representable in binary are not the same as those exactly representable in decimal. Rounding is an issue, as is the interval between floats.

Anyway, you really should read the above paper if you are a working programmer. There is far more to this than one can describe in a few paragraphs on Stack Overflow and the topic is very important.

2
  • As you hint in the 3rd paragraph, the solution is to use a decimal representation rather than a binary representation Feb 27, 2012 at 22:17
  • Not necessarily. Using a printout routine that forces shortest decimal representation that reproduces the binary representation can work in many cases, as can other solutions. There are several good papers on this, and a nice section in Knuth Volume 2. In any case, I'm unsure that the poster was looking for a way to produce a result in accord with pencil-and-paper decimal calculations as much as they were expressing puzzlement with the behavior (and they have yet to say which it was.)
    – Perry
    Feb 27, 2012 at 22:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.