简体   繁体   English

fmod告诉我1的小数部分是1

[英]fmod telling me fractional part of 1 is 1

I'm trying to check if a double variable p is approximately equal to an integer. 我正在尝试检查double变量p是否近似等于整数。 At some point in my code I have 在我的代码中的某个时候

double ip;
cout << setprecision(15) << abs(p) << " " << modf(abs(p), &ip) << endl;

And for a given run I get the printout 对于给定的运行,我得到打印输出

1 1

This seems to say that the fractional part of 1 is 1, am I missing something here or could there be some roundoff problem etc? 这似乎是说1的小数部分是1,是我在这里遗漏了一些东西还是可能存在一些舍入问题等?

Note: I'm not including the whole code since the origin of p is complicated and I'm just asking if this is a familiar issue 注意:由于p的来源很复杂,因此我不包括整个代码,我只是在问这是否是一个熟悉的问题

could there be some roundoff problem etc? 是否会有一些舍入问题等?

There certainly could. 当然可以。 If the value is very slightly less than 1, then both its value and its fractional part could be rounded to 1 when displayed. 如果该值非常小于1,则显示时其值及其小数部分都可以取整为1。

the origin of p is complicated p的由来很复杂

Then it's very likely not to be an exact round number. 那么很可能不是确切的整数。

You are testing a nearly-1-value, so precision of 15 is not enough to describe it unambiguously. 您正在测试接近1的值,因此15的精度不足以明确地描述它。

This code shows your problem clearly: 此代码清楚地显示了您的问题:

#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>
using namespace std;

int main() {
    double ip, d = nextafter(1., .0); // Get a double just smaller than 1
    const auto mp = std::numeric_limits<double>::max_digits10;
    cout << 15 << ": " << setprecision(15)
        << abs(d) << " " << modf(abs(d), &ip) << '\n';
    cout << mp << ": " << setprecision(mp)
        << abs(d) << " " << modf(abs(d), &ip) << '\n';
}

On coliru: http://coliru.stacked-crooked.com/a/e00ded79c1727299 在coliru上: http ://coliru.stacked-crooked.com/a/e00ded79c1727299

15: 1 1
17: 0.99999999999999989 0.99999999999999989

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM