以下代码哪里出错了:import numpy as np from scipy.integrate import odeint from matplotlib import animation import matplotlib.pyplot as plt def f(y,t,G,M): return np.array([y[1], y[0]*y[3]**2-G*M/y[0]**2, y[3], -2*y[1]*y[3]/y[0]]) #初始条件 v0=0 #解微分方程 G,M=6.67e-11,2e30 theta0=0 t= np.linspace(0,20,200) r0=1.5e11 y0=[r0,0,theta0,np.sqrt(2*G*M/r0**3)] res=odeint(f,y0,t,args=(G,M)) x=res[:,0]*np.sin(res[:,2]) y=res[:,0]*np.cos(res[:,2]) #画图 fig=plt.figure() plt.axis([-5*r0,5*r0,-5*r0,5*r0]) myline,=plt.plot([],[],'b',lw=2) mypoint,=plt.plot([],[],'ro',ms=20) def animate(i): mypoint.set_data([x[i],y[i]]) myline.set_data(x[:i],y[:i]) return mypoint,myline anim=animation.FuncAnimation(fig,animate,frames=len(t),interval=100) plt.show()
时间: 2023-11-22 19:55:10 浏览: 82
python应用-scipy,numpy,sympy计算微积分
代码中缺少空格,应该在第一行的 import numpy as np 和 from scipy.integrate import odeint 之间加一个空格。正确代码如下:
```
import numpy as np
from scipy.integrate import odeint
from matplotlib import animation
import matplotlib.pyplot as plt
def f(y,t,G,M):
return np.array([y[1],
y[0]*y[3]**2-G*M/y[0]**2,
y[3],
-2*y[1]*y[3]/y[0]])
#初始条件 v0=0
#解微分方程
G,M=6.67e-11,2e30
theta0=0
t= np.linspace(0,20,200)
r0=1.5e11
y0=[r0,0,theta0,np.sqrt(2*G*M/r0**3)]
res=odeint(f,y0,t,args=(G,M))
x=res[:,0]*np.sin(res[:,2])
y=res[:,0]*np.cos(res[:,2])
#画图
fig=plt.figure()
plt.axis([-5*r0,5*r0,-5*r0,5*r0])
myline,=plt.plot([],[],'b',lw=2)
mypoint,=plt.plot([],[],'ro',ms=20)
def animate(i):
mypoint.set_data([x[i],y[i]])
myline.set_data(x[:i],y[:i])
return mypoint,myline
anim=animation.FuncAnimation(fig,animate,frames=len(t),interval=100)
plt.show()
```
阅读全文