繁体   English   中英

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

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

我必须找到函数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 ++中,float是单精度的。 使用double而不是float应该给你类似的输出。

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

Coliru上运行此示例:

#include <cmath>
#include <cstdio>

int main()
{
    float pf = 0.84567f;
    printf("%.6f\n",pf/((1-pf)*(1-pf)));

    double pd = 0.84567;
    printf("%.6f\n",pd/((1-pd)*(1-pd)));

    return 0;
}

证明了区别:

35.505867
35.505874

暂无
暂无

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

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