Consider the following function:
auto f(double a, double b) -> int
{
return std::floor(a/b);
}
So I want to compute the largest integer k
such that k * b <= a
in a mathematical sense. As there could be rounding errors, I am unsure whether the above function really computes this k
. I do not worry about the case that k
could be out of range. What is the proper way to determine this k
for sure?
Division produces a/b, calculated exactly then rounded to a valid double number. If a/b >= n then it cannot be rounded to something less than n. If a/b < n, say 7.9999999999, then it could be rounded to 8 a priori, but you can prove that n is never the nearest floating point number.
The problem is that float division is not exact.
a/b
can give 1.9999
instead of 2
, and std::floor
can then give 1
.
One simple solution is to add a small value prior calling std::floor
:
std::floor (a/b + 1.0e-10);
Result:
result = 10 while 11 was expected
With eps added, result = 11
Test code:
#include <iostream>
#include <cmath>
int main () {
double b = atan (1.0);
int x = 11;
double a = x * b;
int y = std::floor (a/b);
std::cout << "result = " << y << " while " << x << " was expected\n";
double eps = 1.0e-10;
int z = std::floor (a/b + eps);
std::cout << "With eps added, result = " << z << "\n";
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.