问题描述
我对 python 比较陌生,所以请原谅我的代码中的任何废话。我正在尝试使用我的古典力学教科书(John R. Taylor 的古典力学)中的方程在 python 中编程一个行星的圆形轨道(我只使用了天王星和太阳的质量)。我想我可以只使用这些方程并绘制一个函数 y,它等于一个圆的方程,其中 c_squared 是半径,x 是用于绘制圆的值数组。让我知道如何改进代码,或者我什至朝着正确的方向前进。
...
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
import math
fig = plt.figure()
ax = fig.add_subplot()
m_uranus = 8.681 * 10**(25)
m_sun = 1.989 * 10 **(30)
G = 6.67430 * 10**(-11)
mu = (m_uranus * m_sun)/(m_uranus + m_sun)
l = (1.7 * 10**(42)) * 1000 * 24 * 60 * 60
ang_squared = l ** 2
c = (ang_squared)/(G * m_uranus * m_sun * mu)
c_squared = c**2
print(m_sun,mu,m_uranus,ang_squared,c)
x = np.arange(-100,100,1)
y = math.sqrt(c_squared - x)
plt.plot(x,y)
plt.show()
...
解决方法
正如@JohanC 所提到的,使用 numpy np.sqrt() 而不是 math.sqrt() 将修复您的错误,这里修复了(删除了不必要的库) ):
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot()
m_uranus = 8.681 * 10 ** 25
m_sun = 1.989 * 10 ** 30
G = 6.67430 * 10 ** (-11)
mu = (m_uranus * m_sun) / (m_uranus + m_sun)
l = (1.7 * 10 ** 42) * 1000 * 24 * 60 * 60
ang_squared = l ** 2
c = ang_squared / (G * m_uranus * m_sun * mu)
c_squared = c ** 2
print(m_sun,mu,m_uranus,ang_squared,c)
x = np.arange(-100,100,1)
y = np.sqrt(c_squared - x)
plt.plot(x,y)
plt.show()
希望能帮到你!