Floor vs int cast difference

511 views Asked by At

I have a weird problem. Here's part of my code:

int temp=1100;
int foo=floor(0.03*temp);
int foo1=0.03*temp;
if(foo-foo1){
        cout<<foo<<endl;
        cout<<foo1<<endl;
}

If 3% of temp = integer then foo differs from foo1 by 1.
For example:
1100*0.03=33.
foo=33
foo1=32.
In addition if i write it like that :

int foo=floor(0.03*1100);
int foo1=0.03*1100;

There is no such problem.
Why?

1

There are 1 answers

0
DerrickHo328 On BEST ANSWER

Floating point numbers have trouble rendering decimal places. It is more of an approximation.

2**-6 + 2**-7 + 2**-8 + 2**-9 + 2**-11 + 2**-13 + 2**-14 + 2**-15 + 2**-20 + 2**-22 + 2**-26 = 0.0299999863

Using binary, I drove the accuracy to 26 binary. I got close to 0.03 but not quite. In my example I chose to be under 0.03 but I could have gone a little above (i.e. 0.03000001. I don't think it is possible to represent 0.03 perfectly in floating point notation.

Multiplying 0.03 by any number produces yet another approximation. Casting to type int will cut out everything after the decimal place. I assume the implementation of floor is more elegant. Your compiler probably choose a floating point value of 32.99999 so and int would make 32.