python - 数学域错误 math 与 cmath 不同的行为

标签 python math

我的程序中有以下代码行:

theta=(180/math.pi)*0.5*math.asin((9.8*dist)/(vel**2))

当我在 import math 之后使用上面的代码时,它会给我以下数学域错误:

Traceback (most recent call last):
File "traj.py", line 36, in <module>
processCase(caseNumber,V,D) 
File "traj.py", line 20, in processCase
theta=(180/math.pi)*0.5*math.asin((9.8*dist)/(vel**2))
ValueError: math domain error

输入是:

vel= 119 dist= 1445

是什么导致了这个错误。当我使用 import cmath 时,错误消失但我得到一个复数作为输出。这是为什么?

最佳答案

由于将 (9.8*dist)/(vel**2) 舍入为大于 1.0 的值的浮点错误,asin 函数给出了域错误。

您可以通过将 math.asin 调用中的数字限制为最大值 1.0 来解决此问题,无论四舍五入如何。您可以使用 Decimalarithmetic 以适当的“数学”方式进行计算,但会对性能和复杂性产生巨大影响。

我的建议是在 asin 调用中简单地调用 min:

theta=(180/math.pi)*0.5*math.asin(min(1.0, ((9.8*dist)/(vel**2)) )  

关于python - 数学域错误 math 与 cmath 不同的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24399893/

相关文章:

python - 在pytest fixture 中模拟stdlib函数

python - 如何调整子图的高度和宽度以紧密配合?

ruby - 如何模拟 Fixnum 变量的整数溢出?

algorithm - 在给定范围内有多少个数字具有最大数量的唯一质因数

java - 子弹没有射出枪

javascript - 将动画重写为基于时间的(而不是基于平速的)

python - 如何喂占位符?

python - scrapy蜘蛛: output in chronological order

math - 什么样的编程需要数学?

python - 当我在 Pandas 中使用 df.corr 时,我的一些专栏丢失了