floating point overflow

hello and sorry for my english. why does this piece of code:

1
2
3
4
5
6
7
8
for (int i=15;i<30;i++)
    {
        long double A=2013;
        long double B=pow(10,i);
        long double C=A+B-B;
        cout<<A<<"  "<<B<<"  "<<C;
        cout<<endl;
    }


give me this?:

2013 1e+15 2013
2013 1e+16 2013
2013 1e+17 2013
2013 1e+18 2013
2013 1e+19 2013
2013 1e+20 2016
2013 1e+21 1984
2013 1e+22 2048
2013 1e+23 0
2013 1e+24 0
2013 1e+25 0
2013 1e+26 0
2013 1e+27 0
2013 1e+28 0
2013 1e+29 0

can you help me ? thanks

thanks

http://en.wikipedia.org/wiki/Scientific_notation
Wikipedia wrote:
Scientific notation is a way of writing numbers that are too big or too small to be conveniently written in decimal form
as 1015 is too big to be written conveniently and have simple scientific form, it will show it as such.

Zeroes and strange values are here because of precision problems. Doubles store about 20 significant digits. Everything after that can be lost. In your case it leads to fact that 1e+23 + 2013 = 1e+23 because next representanle number is larger that that.
Last edited on
ok thanks. please look this http://www.zator.com/Cpp/E2_2_4a1.htm . why does this application give me 10000000000002012 when i insert 10000000000002013 ? can you explain me or give me a link to get the answer ? why does the ieee-754 round off the input?
Ok. Let me get you an exmple in decimal:
Pretend you have some datatype which lets you store only 5 significant digits + 2 digits of exponent. Value 1020304 can be storead as 10203e+02 (only 5 digits is stored)
Now add 123. You will get 10204e+02 because there is no place to write other digits and they are lost.
Now remember that computer uses binary and there is some numeric system quirks.
mm ok, I understand, thank you very much :)
Topic archived. No new replies allowed.