[英]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
应该给你类似的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.