数学域误差不会使用带有变量的各种三角函数加起来



所以我是python的新手,我用它来做几个类,我正在制作程序来运行计算。 在这里,我有三维向量的代码,我遇到了一个问题,但是当我输入 Fx=0 Fy=-6 和 Fz=8 的向量时,它在计算变量 s 时给了我一个数学域错误。我手动尝试了数学,工作正常,让它打印错误之前用于 s 的所有变量,并使用数字手动执行数学代码行并检查出来,它适用于几乎所有其他 3d 向量扔给它,我不确定为什么它在那里崩溃。另外,如果您对如何做得更好有任何建议,我都是耳朵(尽管我很欣赏任何指向代码或要导入的点的链接,但我必须编写代码本身才能将其用于课堂)。 代码如下:

#blue triangle
#if else
import math
a=input('what is the altitude angle theta z:')
s=input('what is the swing angle phi:')
F=input('what is the magnitude:')
Fx=input('what is the Fx component:')
Fy=input('what is the Fy component:')
Fz=input('what is the Fz component:')

#Blue triangle functions (Magnitude, Theta z, phi)
if a !='' and s!='' and F!='':
print('---------------------------------------------------------------------------------------')
#a = input('what is the altitude angle theta z:')
#s = input('what is the swing angle phi:')
#F = input('what is the magnitude:')

a=float(a)
s=float(s)
F=float(F)

Sa = math.sin(math.radians(a))
Ca = math.cos(math.radians(a))
Ss = math.sin(math.radians(s))
Cs = math.cos(math.radians(s))

Fx = F*Sa*Cs
Fy = F*Sa*Ss
Fz = F*Ca

print('              Fx=',Fx)
print('              Fy=',Fy)
print('              Fz=',Fz)
print('              Unit vector <',round(Fx/F,4), round(Fy/F,4), round(Fz/F,4), '>')

Fx=''



#Blue triangle functions (Fx,Fy,Fz)
if Fx!='' and Fy!='' and Fz!='':
print('---------------------------------------------------------------------------------------')

Fx=float(Fx)
Fy=float(Fy)
Fz=float(Fz)

F=math.sqrt((Fx**2)+(Fy**2)+(Fz**2))
a=math.degrees(math.acos(Fz/F))
s=math.degrees(math.asin((Fy/(F*math.sin(math.radians(a))))))
print('              Force=',F)
print('              Altitude of theta z=',a)
print('              planar swing angle phi=',s)
print('              Unit vector <',round(Fx/F,4), round(Fy/F,4), round(Fz/F,4), '>')

print('done')

您得到的错误来自浮点数学不精确 - 正如官方 python 文档中所记录的那样

如果你把你的语句分成几个部分并打印中间参数,你可以看到 1) 错误来自哪个命令,2) 该命令的输入值是什么。

arg = Fy/(F*math.sin(math.radians(a)))
print(arg)
arg2 = math.asin(arg) # the error is on this line
s = math.degrees(arg2)

从分析上讲,arg在这里应该正好是 -1,但是当你打印它时,你会看到它的值为-1.0000000000000002(请参阅上面关于浮点数学不精确的链接......由于您不能取 1 或 <-1>数字的asin,因此会出现数学域错误。一种解决方案是在将其传递给asin函数之前将其裁剪到有效范围。

arg = Fy/(F*math.sin(math.radians(a)))
arg_clipped = max([-1, min([1, arg])])
arg2 = math.asin(arg_clipped)
s = math.degrees(arg2)

大多数情况下,裁剪不会执行任何操作,除了这些极端情况,在这些极端情况下,您处于完全相同的直角并且参数值正好为 1 或 -1。

我还建议通过计算将内容保留为弧度,如果您需要以度为单位显示值,只需在打印时将其转换为度。

另请参阅python中的精确三角和Python余弦函数精度。

最新更新