This program is designed to figure the accuracy of the floating-point numbers. The idea is simple. Compute the following until the numbers are equal:
1.0 == 1.5 (1 + 1/2 or 1 + 1/21) (1.1 binary)
1.0 == 1.25 (1 + 1/4 or 1 + 1/22) (l.oi binary)
1.0 == 1.125 (1 + 1/8 or 1 + 1/23) (1.001 binary)
1.0 == 1.0625 (1 + 1/16 or 1 + 1/24) (1.0001 binary)
1.0 == 1.03125 (1 + 1/32 or 1 + 1/25) (1.00001 binary)
That will give us the number of digits of accuracy.
This program was run on a PC-class machine with 32-bit floating-point. So how many binary digits would you expect in a 32-bit float format?
This program does not give the right answer. Why?
1 /************************************************
2 * accuracy test. *
3 * *
4 * This program figures out how many bits *
5 * accuracy you have on your system. It does *
6 * this by adding up checking the series: *
7 * *
8 * 1.0 == 1.1 (binary) *
9 * 1.0 == 1.01 (binary) *
10 * 1.0 == 1.001 (binary) *
11 * .... *
12 * *
13 * Until the numbers are equal. The result is *
14 * the number of bits that are stored in the *
15 * fraction part of the floating point number. *
16 ************************************************/
17 #include <iostream>
18
19 int main()
20 {
21 /* two numbers to work with */
22 float number1, number2;
23
24 /* loop counter and accuracy check */
25 int counter;
26
27 number1 = 1.0;
28 number2 = 1.0;
29 counter = 0;
30
31 while (number1 + number2 != number1) {
32 ++counter; // One more bit accurate
33
34 // Turn numbers like 0.1 binary
35 // into 0.01 binary.
36 number2 = number2 / 2.0;
37 }
38 std::cout << counter << " bits accuracy.\n";
39 return (0);
40 }