我尝试计算与numpy的弹性碰撞,但在编写脚本时发现丢失:
def elasticCollisionFormular():
while True:
try:
A = np.array([[m1,m2],[0.5*m1,0.5*m2]])
B = np.array([[v1,v2],[v1**2,v2**2]])
C = np.array([[m1,m2],[0.5*m1,0.5*m2]])
D = np.linalg.solve(A*B,C)
except:
print('An error occured. Retrying...')
continue
else:
return D
break
我得到的D不正确,应该如何安排D = np.linalg.solve(A*B,C)
?
一个示例及其正确答案:
m1 = 3
m2 = 1
v1 = 4
v2 = 8
v₁' = -2 and 4
v₂' = 10 and -8
编辑: 完整代码在这里:
import numpy as np
def ask_for_m1():
while True:
try:
m1 = int(input('Enter the mass of object 1 :'))
except:
print('An error occured, please try again')
continue
else:
return m1
break
def ask_for_m2():
while True:
try:
m2 = int(input('Enter the mass of object 2 :'))
except ImportError:
print('An error occured, please try again')
continue
else:
return m2
break
def ask_for_v1():
while True:
try:
v1 = int(input('Enter the staring speed of object 1 :'))
except:
print('An error occured, please try again')
continue
else:
return v1
break
def ask_for_v2():
while True:
try:
v2 = int(input('Enter the staring speed of object 2 :'))
except:
print('An error occured, please try again')
continue
else:
return v2
break
def elasticCollisionFormular():
while True:
try:
A = np.array([[m1,m2],[0.5*m1,0.5*m2]])
B = np.array([[v1,v2],[v1**2,v2**2]])
C = np.array([[m1,m2],[0.5*m1,0.5*m2]])
D = np.linalg.solve(A*B,C)
except:
print('An error occured. Retrying...')
continue
else:
return D
break
#start of program
while True:
m1 = ask_for_m1()
m2 = ask_for_m2()
v1 = ask_for_v1()
v2 = ask_for_v2()
D = elasticCollisionFormular()
print(D)