python - 计算方程时的数学域错误
问题描述
我是一名 Python 初学者,我正在编写一个代码,该代码从用户那里获取输入并使用它来运行计算,直到某个变量达到 0:
import math
ind = 1
x_i = 1
dt = 0.01
k = 11.5
r_out = 0.889
w = 0.03175
dL = 30
m = float(input("Enter m: "))
v_i = float(input("Enter v_i: "))
t =[0]
x = [x_i]
v = [v_i]
Fc = []
while (v_i > 1):
Fc_i = (k * v_i ** 2 * math.cos(math.atan(30 / x_i)) / 2 * (math.sqrt(r_out ** 2 - (w / math.pi) * (math.sqrt(x_i ** 2 + dL ** 2)))))
Fc.append(Fc_i)
x.append(x_i + v_i * dt + 0.5 * (-Fc_i / m) * dt)
v.append(v_i - (Fc_i / m))
t.append(dt * ind)
print(Fc_i, v_i, x_I)
ind += 1
Fc_i = Fc[-1]
x_i = x[-1]
v_i = v[-1]
当我输入两个值(在本例中为m = 19958.06
和v_i = 69.444
)时,代码在前 100 个循环中运行得非常好,但随后给了我一个错误:
Fc_i = (k * v_i ** 2 * math.cos(math.atan(30 / x_i)) / 2 * (math.sqrt(r_out ** 2 - (w / math.pi) * (math.sqrt(x_i ** 2 + dL ** 2)))))
ValueError: math domain error
我检查了所有变量值并尝试使用我在代码中复制的公式自己计算方程,我没有遇到任何奇怪的事情。代码/我将变量传递给下一个循环的方式是否有错误?
解决方案
问题出现在您计算的这一部分
math.sqrt(r_out ** 2 - (w / math.pi) * (math.sqrt(x_i ** 2 + dL ** 2)))
查看此错误时的值
r_out = 0.889
w = 0.03175
x_i = 72.2987746569653
dL = 30
如果我们将这些插入计算并开始求解
math.sqrt(0.889 ** 2 - (0.03175 / math.pi) * (math.sqrt(72.2987746569653 ** 2 + 30 ** 2)))
math.sqrt(0.889 ** 2 - (0.03175 / math.pi) * (math.sqrt(5227.112816898649 + 900)))
math.sqrt(0.889 ** 2 - (0.03175 / math.pi) * (math.sqrt(6127.112816898649)))
math.sqrt(0.889 ** 2 - (0.03175 / math.pi) * (78.27587634066225))
math.sqrt(0.889 ** 2 - (0.010106338886335354) * (78.27587634066225))
math.sqrt(0.790321 - (0.010106338886335354) * (78.27587634066225))
#now here multiplaction takes precedence over subtraction
math.sqrt(0.790321 - 0.7910825329236124)
math.sqrt(-0.0007615329236123625)
#This is an error as negative number cannot have a real root.
如果你的意思是r_out ** 2 - (w / math.pi)
在乘法之前发生,那么你需要在它周围加上括号
Fc_i = (k * v_i ** 2 * math.cos(math.atan(30 / x_i)) / 2 * (
math.sqrt((r_out ** 2 - (w / math.pi)) * (math.sqrt(x_i ** 2 + dL ** 2)))))