简体   繁体   English

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

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

I had to find the result of a function f(x) = x / (1-x)^2 , where 0 < x < 1 . 我必须找到函数f(x) = x / (1-x)^2 ,其中0 < x < 1 The value had to be formatted up to 6 decimal places only. 该值必须格式化为最多6个小数位。

Here is my C++ code: 这是我的C ++代码:

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

And I did for the same in Python: 我在Python中做了同样的事情:

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

For some values of x, both the programs give different answers. 对于x的某些值,两个程序给出不同的答案。

For example, for x = 0.84567 , 例如,对于x = 0.84567

C++ gives 35.505867 and Python gives 35.505874 C ++给出35.505867 ,Python给出35.505874

Why does this happen? 为什么会这样?
According to solution, the Python answers are right, while C++ answers are wrong. 根据解决方案,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;
}

sample output: 样本输出:

35.505867
35.505874

Conclusion: 结论:

Python is using doubles, you're using floats. Python正在使用双打,你正在使用浮点数。

Python has implemented IEEE 754 double-precision, so its output is closer to real answer. Python已经实现了IEEE 754双精度,因此它的输出更接近实际答案。

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

Almost all machines today (November 2000) use IEEE-754 floating point arithmetic, and almost all platforms map Python floats to IEEE-754 “double precision”. 今天(2000年11月)几乎所有机器都使用IEEE-754浮点运算,几乎所有平台都将Python浮点数映射到IEEE-754“双精度”。

In C++ float is single-precision. 在C ++中,float是单精度的。 Using double instead of float should give you similar output. 使用double而不是float应该给你类似的输出。

As others have pointed out, floating point numbers in python are implemented using double type in C. See section 5.4 of the Python Documentation. 正如其他人所指出的那样,python中的浮点数是用C中的double类型实现的。参见Python文档的5.4节

Running this example on Coliru : 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;
}

demonstrates the difference: 证明了区别:

35.505867
35.505874

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

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