简体   繁体   中英

solve differential equation in python using scipy

Hello I would like to solve the following first ODE:

dt/dr = +- cos(t)^2/cos(r)^2

I know the solution is : t(r) = t(r) = arctan(tan(r)+_C1), with: pi/2 < t< pi/2 and 0< r< pi/2.

I would like to know how could I improve the code below such my solution resembles the curve that is tending to + infinity on t axis in the image:

一个C值的理想解决方案

My code is:

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);

and my current graphical output is:

current_solution

Not sure if I understand your problem, however it seems that the solutions in the two plots are the same but they are plotted differently. In the "desired solution for one C value"-plot, the y-axis is stretched when compared to the x-axis. In your "current_solution", they are equal.

The two graphs in the question are the same, however they both have different limits. To change the limits you need to do plt.xlim() and plt.ylim() . Setting them to be the same as the desired outcome will give you the same result.

There is one addition to the desired outcome in that the y axis crosses the x axis at 0, rather than the left hand edge of the axis (the default). You can change this by moving the left hand spine:

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()

Which gives:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM