相同的算术运算在 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++浮点数是单精度的。使用 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
相关文章:
- 算术运算的结果类似于:C浮点变量中的1/3
- 更快的C++算术运算
- 为什么循环体中的一个基本算术运算执行得比两个算术运算慢
- 为什么对无符号字符进行算术运算会将它们提升为有符号整数
- 如何在 C++ 中计算字符串的算术运算
- 复数的算术运算
- 具有非常非常大数字的算术运算
- 如何使用C++中的处理器指令来实现快速算术运算
- boost::spirit::x3 phrase_parse 在进入 Vector 之前进行算术运算
- C++中混合数据类型的算术运算
- C++:编译器是否优化整数 + 浮点算术运算?
- 如何在特征中对二维数组的列执行简单的算术运算
- 使用数字列表和算术运算获取目标数字
- C++:“enable_if”用于限制支持特定算术运算的类型
- 如何正确避免 SIGFPE 和算术运算溢出
- 编译器用于编译 128 位整数的基本算术运算的技巧
- 相同的算术运算在 C++ 和 Python 中给出不同的结果
- 使用浮点值和铸造的算术运算的错误结果 - 差异很大,我想这不是准确值的情况(429497)?
- 算术运算打印错误的结果
- 如果算术运算的结果未存储在内存中会发生什么情况