INTERNAL: C code example of finite number (computer) precision
Anonym
Topic:
In a computer, real numbers are represented with finite precision. While in most cases it is safe to assume that the result of an arithmetical operation done on your computer is correct, it is important to remember that this finite-precision representation leads to unavoidable errors, especially when floating-point numbers, which are digital approximations to real numbers, are involved.Discussion:
To understand why floating-point numbers are inherently inaccurate, consider the following:
Floating-point numbers must be made to fit in a space (a string of binary digits in a computer's memory register) that can only hold an integer and a scaling factor.
Floating-point numbers are represented by strings of a limited number of bits, but represent numbers much larger or smaller than that number of digits can be made to express.
In other words, floating-point values are finite-precision approximations of infinitely precise numbers."
2.1 - 2 results in one of these inaccurate situations because the the numbers involved cannot be exactly represented with single precision. However the numbers can be exactly represented with double precision.
This will also occur in C as shown in the following C code:Solution:
void main()
{
float dummy;
dummy = 2.1;
printf( "Same test in C yields: %5.2f \- 2 = %10.8g " , dummy , dummy - 2 );
return;
}
//Same test in C yields: 2.10 - 2 = 0.099999905