c – 为什么我从std :: fmod和std :: remainder获得不同的结果
发布时间:2020-12-16 10:44:18 所属栏目:百科 来源:网络整理
导读:在下面的示例app中,我使用std :: fmod计算从953除以0.1的浮点余数 我期待的是,自953.0 / 0.1 == 9530,那std :: fmod(953,0.1)== 0 我得到0.1 – 为什么会这样? 请注意,使用std :: remainder我得到了正确的结果. 那是: std::fmod (953,0.1) == 0.1 // unexp
在下面的示例app中,我使用std :: fmod计算从953除以0.1的浮点余数
我期待的是,自953.0 / 0.1 == 9530,那std :: fmod(953,0.1)== 0 我得到0.1 – 为什么会这样? 请注意,使用std :: remainder我得到了正确的结果. 那是: std::fmod (953,0.1) == 0.1 // unexpected std::remainder(953,0.1) == 0 // expected 两个功能之间的区别: 根据cppreference.com > std :: fmod计算以下内容: 恰好是值x – n * y,其中n是x / y,其小数部分被截断 > std :: remainder计算以下内容: 恰好是值x – n * y,其中n是最接近精确值x / y的积分值 根据我的输入,我希望两个函数具有相同的输出.为什么不是这样? 范例app: #include <iostream> #include <cmath> bool is_zero(double in) { return std::fabs(in) < 0.0000001; } int main() { double numerator = 953; double denominator = 0.1; double quotient = numerator / denominator; double fmod = std::fmod (numerator,denominator); double rem = std::remainder(numerator,denominator); if (is_zero(fmod)) fmod = 0; if (is_zero(rem)) rem = 0; std::cout << "quotient: " << quotient << ",fmod: " << fmod << ",rem: " << rem << std::endl; return 0; } 输出: quotient: 9530,fmod: 0.1,rem: 0 解决方法
欢迎来到浮点数学.这是发生的事情:十分之一不能用二进制精确表示,就像三分之一不能用十进制精确表示一样.结果,除法产生的结果略低于9530. floor操作产生整数9529而不是9530.然后剩下0.1剩余.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |