Floating Point Precision Questions

Hi all,

I think the one area I lack knowledge in most is when it comes to floating point precision.

I don't understand the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{
int a = 1;
float b = 2.312345678;
double c = 4.59983216;

cout.setf(ios::fixed,ios::floatfield);
cout.precision(20);

cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "c + .00000784 = " << (c+.00000784) << endl;
cout << "b * 2 = " << b*2 << endl;

return 1;
}


The output:
a = 1
b = 2.31234574317932128906
c = 4.59983216000000005863
c + .00000784 = 4.59984000000000037289
b * 2 = 4.62469148635864257812

Why are there strange values at the end of b and c? Does anyone know of a good read with a simple explanation?

Thanks!
Last edited on
What are some common issues to be aware of when dealing with variables that need precise precision?

What are good practices to avoid long-run precision issues?

How can they be prevented?
precise precision
Nice.

Floating point values are stored as pairs of integers (x,y) that represent values x*2^y. This has a few obvious limitations.

You know how you can't fully write down the value 1/3? If you're limited to, say, three digits then you either write down 3.33*10^-1 or 3.34*10^-1, neither of which are the exact value. Floating point representations have the exact same problem, but with other values. For example, 0.1 is a repeating decimal in binary (0.00011).

Another problem is that they can only store a limited number of significant digits. double can represent 10^100 and 10^-100, but it can't represent 10^100+10^-100 since that would require over 600 bits (200/log10(2)). So if you try to perform an operation between two numbers that are too apart in magnitude, the computer will have to do some approximation.

For a more complete (and difficult) look at the subject, see http://docs.sun.com/source/806-3568/ncg_goldberg.html
Topic archived. No new replies allowed.