Floating point types fake numbers

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main (int argc, const char * argv[])
{
    double n1 = 0.0;
    float n2 = 0.0;
    cout << "Insert two floating point numbers." << endl;
    cin >> n1 >> n2;
    cout << n1 << endl << n2 << endl;
    return 0;
}


I have two questions:

1) If I set n1 = 1.22334321 and n2 = 1.178843 the debugger says that n1 = 1.2233432199999999 and n2 = 1.17884302.

Why doesn't it leave the numbers as I entered them?
I want to use the numbers as I entered them. How can I do that?

2) Using the same input as before the output is:


1.22334
1.17884


Why does the compiler round the numbers to five digits after the decimal point?
Floating point type numbers have a limited accuracy:
http://en.wikipedia.org/wiki/Floating_point
For your second question use std::cout.precision(x), where x is the max amount of significant digits you want.
1
2
3
4
5
6
7
int main (int argc, const char * argv[])
{
    double base = 2.3;
    double exp = 1.2345;
    cout << pow(base, exp);
    return 0;
}


In that case, for example, the debugger still says that base = 2.2999999 and exp = 1.23449999999 but the output is correct:


2.7961


How can the pow() function do that?
If you read the article that BlackSheep provided the link to, you might see a lot of clues. Here is another hint:

Floating point numbers are like this:

FloatValue = DesiredVlaue plus or minus a very small amount. This why 2.3 is 2.2999999. However output functions like cout & printf will do the right thing, so 2.3 to 2dp is 2.30

Google DBL_EPSILON for more info, especially how to compares floats & doubles.

HTH
Hello,

just adding the aswer, the cause is the representation of float in system architeture has limits (4 bytes to be right), so sometimes you cannot take the precission of you want.

But you can say "it's only 2 digits: 2.3, how the system cannot represent this?" Cause the system use the another numerical base: the binary system. That's mean the number 2.3 can be a repeating decimal in binary, so it's never precise and need rounding to work. When you use few times the variable there's no problem, but if is in a for loop then could be a monster like the http://www.ima.umn.edu/~arnold/455.f96/disasters.html

See in the link how the system represent you value: http://www.h-schmidt.net/FloatConverter/IEEE754.html I hope this help you better understand(y)

sorry for the bad english
Topic archived. No new replies allowed.