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

math domain error doesnt add up using various trig functions with variable

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

#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')

您收到的错误来自 floating point math being inexact - as documented in the official python docs too

如果将语句分成几个部分并打印中间参数,您可以看到 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(参见上面关于浮点数学的 link不准确...)。由于您不能对大于 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。

我还建议在计算过程中以弧度为单位,如果您需要以度数显示值,只需在打印时将其转换为度数即可。

另见 Accurate trig in python and Python cosine function precision