fmod不正确吗?

编程入门 行业动态 更新时间:2024-10-25 21:24:16
本文介绍了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不正确吗?

本文发布于:2023-11-10 06:09:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574562.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不正确   fmod

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!