[英]solve differential equation in python using scipy
您好,我想解决以下第一个ODE:
dt / dr = +-cos(t)^ 2 / cos(r)^ 2
我知道解决方案是:t(r)= t(r)= arctan(tan(r)+ _ C1),其中:pi / 2 <t <pi / 2和0 <r <pi / 2。
我想知道如何改善下面的代码,使我的解决方案类似于图像中t轴趋于+无穷大的曲线:
我的代码是:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
"""
Equations to be solved:
boundary conditions:
-pi/2 << t << pi/2
0 <= r <= pi/2
Equation:
dt/dr = +- cos^2(t)/cos^2(r)
Solution :
t(r) = arctan(tan(r) +_C1)
"""
def dt_dr(t,r):
return (cos(t)**2)/(cos(r)**2)
rs = np.linspace(0,pi/2,1000)
t0 = 0.0 #the initial condition
ts = odeint(dt_dr,t0,rs)
ts = np.array(rs).flatten()
plt.rcParams.update({'font.size': 14})
plt.xlabel("r")
plt.ylabel("t")
plt.plot(rs,ts);
我当前的图形输出是:
不知道我是否理解您的问题,但是似乎两个图中的解决方案是相同的,但是绘制的方式却不同。 在“对于一个C值的理想解”图中,y轴与x轴相比被拉伸。 在您的“ current_solution”中,它们是相等的。
问题中的两个图是相同的,但是它们都有不同的限制。 要更改限制,您需要执行plt.xlim()
和plt.ylim()
。 将它们设置为与期望的结果相同将给您相同的结果。
y轴与x轴在0处而不是x轴的左边缘(默认值)相交,从而为期望的结果提供了一个补充。 您可以通过移动左脊椎来更改此设置:
rs = np.linspace(0, pi/2, 1000)
t0 = 0.0 #the initial condition
ts = odeint(dt_dr, t0, rs)
plt.rcParams.update({'font.size': 11})
plt.xlabel("t")
plt.ylabel("r")
plt.plot(ts, rs)
# Change axis limits
plt.ylim(0,0.6)
plt.xlim(-1.5,1.5)
# Move left spine to x=0
ax = plt.gca()
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
plt.show()
这使:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.