我是python的新手,我有python的精度问题,这是我以前在c++中没有的问题,代码是python的
import math
def f(x):
return math.sqrt(x)
print((38 / (math.sqrt(38) * math.sqrt(38))))
print(38 / (f(38) * f(38)))
print(math.acos(38 / (math.sqrt(38) * math.sqrt(38))))
print(math.acos(38 / (f(38) * f(38))))结果是
Traceback (most recent call last):
File "C:\Users\dell\PycharmProjects\pythonProject2\main.py", line 10, in <module>
print(math.acos(38 / (math.sqrt(38) * math.sqrt(38))))
ValueError: math domain error
1.0000000000000002
1.0000000000000002对于c++
#include <iostream>
#include <cmath>
using namespace std;
double f(double x);
int main()
{
cout <<38/(f(38)*f(38))<<endl;
cout <<38/(sqrt(38)*sqrt(38))<<endl;
cout <<acos(38/(f(38)*f(38)))<<endl;
cout <<acos(38/(sqrt(38)*sqrt(38)))<<endl;
return 0;
}
double f(double x)
{
return sqrt(x);
}结果是
1
1
nan
0这可能会导致崩溃
发布于 2021-11-12 17:51:04
当涉及到浮点运算时,不同的编程语言可能会有不同的表现。它可能会涉及到优化、acos等函数的内部实现。
首先,请注意,在C++中,对于超出范围的值,acos会返回特殊值nan,而在Python中,它会抛出ValueError异常。但是,您可以很容易地获得C++行为,如下所示:
import math
def my_acos(x):
try:
return math.acos(x)
except ValueError:
return float("nan")此外,您可以添加舍入以接受稍微超出范围的值。您的数字在小数点后有15个零,因此让我们四舍五入到15位(为了演示):
import math
def my_acos(x):
try:
return math.acos(round(x, 15))
except ValueError:
return float("nan")通过这种修改,您的代码将产生您所期望的结果。
https://stackoverflow.com/questions/69946976
复制相似问题