[英]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.