Author |
Topic: strange results of float to int conversion (Read 669 times) |
|
allbatros
Newbie
Posts: 50
|
|
strange results of float to int conversion
« on: May 10th, 2007, 4:22am » |
Quote Modify
|
float a=5.2; cout<<int(a*10); output comes out to be 51. why??
|
|
IP Logged |
|
|
|
Grimbal
wu::riddles Moderator Uberpuzzler
Gender:
Posts: 7527
|
|
Re: strange results of float to int conversion
« Reply #1 on: May 10th, 2007, 4:30am » |
Quote Modify
|
Because computer speak in binary and 0.2 is 1/5, which cannot be represented exactly in binary, at least not with a limited number of bits. Just like 1/3 cannot be represented in decimal. It is like if in base 10 you do float a=5.3333333333; cout<<int(a*3); You would expect 16 but actually you get 15.9999999999 and that is rounded down to 15. It can happen in accounting applications that use floats for amounts. Calculations with cents have small errors. If they are not rounded off, you might get a client account that is back to 0.00 but with a small error. If it happens to be slightly positive, it will not test equal to zero and the program will happily send a reminder for an amount of 0.00. (with a fine of 5.00).
|
« Last Edit: May 10th, 2007, 4:40am by Grimbal » |
IP Logged |
|
|
|
Grimbal
wu::riddles Moderator Uberpuzzler
Gender:
Posts: 7527
|
|
Re: strange results of float to int conversion
« Reply #2 on: May 10th, 2007, 4:54am » |
Quote Modify
|
If you enter in an Excel column 18 -8.8 -8.8 -0.4 and you sum it, you don't get zero.
|
|
IP Logged |
|
|
|
allbatros
Newbie
Posts: 50
|
|
Re: strange results of float to int conversion
« Reply #3 on: May 10th, 2007, 6:37am » |
Quote Modify
|
i got the inkling of logic behind but could u elaborate it more. i.e. in terms of bit representations in memory(23 for abccisa and 8 for mantissa). how our computing machine performs addition, conversion, (interpretation in decimal). like another similar result is with float a=5.3; cout<<int(a*10)<<endl; result is 5.3 but with float a=5.2; a+=0.1; cout<<int(a*10)<<endl; result is 5.2
|
|
IP Logged |
|
|
|
towr
wu::riddles Moderator Uberpuzzler
Some people are average, some are just mean.
Gender:
Posts: 13730
|
|
Re: strange results of float to int conversion
« Reply #4 on: May 10th, 2007, 6:53am » |
Quote Modify
|
What you could do is take an actual look at the bits. Reinterpret the memory of the float as an int int b = *(int *)&a; and then print the bits for( int i=31; i 0; i++) cout << ((b >> i) & 1); cout <<endl; (It's also interesting to look at +0 and -0, as float they have a different representation)
|
« Last Edit: May 10th, 2007, 6:54am by towr » |
IP Logged |
Wikipedia, Google, Mathworld, Integer sequence DB
|
|
|
|