Returning incorrect values of floor function in C++

Viewed 652

The code:

    cout << log(25.0/9.0)/log(5.0/3.0) << endl << floor(log(25.0/9.0)/log(5.0/3.0));

results:

2
1

Why does C++ considers floor(2) = 1?

What I tried: When saving the fraction in a float it returns the correct value:

float a = log(25.0/9.0)/log(5.0/3.0);
cout << a << endl << floor(a);

results:

2
2
3 Answers

Set your precision. floor is correct;

std::cout << std::fixed << std::setprecision(20) << std::endl << log(25.0 / 9.0) / log(5.0 / 3.0) << std::endl << floor(log(25.0 / 9.0) / log(5.0 / 3.0)) << std::endl;

float a = log(25.0 / 9.0) / log(5.0 / 3.0);
std::cout << std::fixed << std::setprecision(20) << std::endl<< a << std::endl << floor(a) << std::endl;

double b = log(25.0 / 9.0) / log(5.0 / 3.0);
std::cout << std::fixed << std::setprecision(20) << std::endl << b << std::endl << floor(b) << std::endl;

this produces

1.99999999999999955591 1.00000000000000000000

2.00000000000000000000 2.00000000000000000000

1.99999999999999955591 1.00000000000000000000

I complied and checked the whole code and let me share my analysis with you.

If you do log(25.0/9.0)/log(5.0/3.0) division directly the compiler treats it as double and the double division result is equal to 1.9999999999999996. If it is rounded it will become 2 and if floor operation is done on this it will become 1 as floor() function in C++ returns the largest possible integer value which is less than or equal to the given argument. In this example it will always return 1.

If the division log(25.0/9.0)/log(5.0/3.0) is treated as float it will result in 2.0000000039152304 (treating each operand as float and storing result in double for understanding) hence in this case round and floor operation will have same result that is 2.

Good Luck

I had same problem two days ago when I was solving a problem on Codeforces. I was using floor function and its returning its different value. I went to google and found some answers here on stackoverflow telling me to use cout << std::fixed, but this function will return float values with decimal point which is not accepted on Codeforces. After a little bit of google search I found this following formula to calculate floor value of a/b.

floor = (a/b) + ((a%b)!=0)

Hope this helps :)

Related