本文介绍了fmod不正确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下双打, fmod
返回正确的值吗?
Given the following doubles, does fmod
return the correct value?
double x = .090;
double y = .003;
double r = fmod(x, y);
// r = 0.0029999999999999949
为什么r = 0?
推荐答案
由于与大多数小数部分一样,这些数字不能用二进制浮点格式精确表示.要查看实际使用的值:
Because, like most decimal fractions, these numbers can't be represented exactly by a binary floating point format. To see what values are actually being used:
#include <cstdio>
int main() {
printf("%.20f %.20f\n", .090, .003);
}
Output: 0.08999999999999999667 0.00300000000000000006
这些小的舍入误差意味着第一个值略小于第二个值的精确倍数,因此您可以看到结果.
These small rounding errors mean that the first value is slightly less than an exact multiple of the second, hence the result you see.
您可能希望允许较小的错误容忍度:
You may want to allow a small tolerance for error:
if (r > y - some_small_value) {
r = 0;
}
这篇关于fmod不正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!