相同的算术运算在 C++ 和 Python 中给出不同的结果

The same arithmetic operations give different results in C++ and Python

本文关键字:结果 算术运算 C++ Python      更新时间:2023-10-16

我必须找到函数f(x) = x / (1-x)^2的结果,其中0 < x < 1 。该值的格式必须仅保留6位小数。

这是我C++代码:

float x; scanf("%f",&x);
printf("%.6f",x/((1-x)*(1-x)));

我在 Python 中也做了同样的事情:

 x = float(input()) 
 print ("%.6f" % (x/((1-x)**2)))

对于 x 的某些值,两个程序都会给出不同的答案。

例如,对于x = 0.84567

C++提供35.505867,Python提供35.505874

为什么会这样?
根据解决方案,Python的答案是正确的,而C++答案是错误的。

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
int main()
{
    const char data[] = "0.84567";
    float x; 
    sscanf(data, "%f",&x);
    double x2;
    sscanf(data, "%lf",&x2);
    std::cout << std::setprecision(8) << (x/((1-x)*(1-x))) << std::endl;
    std::cout << std::setprecision(8) << (x2/((1-x2)*(1-x2))) << std::endl;
}

示例输出:

35.505867
35.505874

结论:

Python正在使用双精度,你正在使用浮点数。

Python 已经实现了 IEEE 754 双精度,因此其输出更接近真实答案。

来自文档:https://docs.python.org/3/tutorial/floatingpoint.html#representation-error

今天(2000年11月)几乎所有机器都使用IEEE-754浮点 算术,几乎所有平台都将Python浮点映射到IEEE-754 "双精度"。

在C++浮点数是单精度的。使用 double 而不是 float 应该会给你类似的输出。

正如其他人所指出的,python中的浮点数是使用C中的double类型实现的。请参阅 Python 文档的第 5.4 节。

在 Coliru 上运行此示例:

#include <cmath>
#include <cstdio>
int main()
{
    float pf = 0.84567f;
    printf("%.6fn",pf/((1-pf)*(1-pf)));
    double pd = 0.84567;
    printf("%.6fn",pd/((1-pd)*(1-pd)));
    return 0;
}

演示了差异:

35.505867
35.505874