【问题标题】:solve differential equation in python using scipy使用 scipy 在 python 中求解微分方程
【发布时间】:2019-04-09 19:50:30
【问题描述】:

您好,我想解决以下第一个 ODE:

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

我知道解决方案是:t(r) = t(r) = arctan(tan(r)+_C1),其中: 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);

我当前的图形输出是:

【问题讨论】:

  • 我想你想把ts = np.array(rs).flatten()改成rs = np.array(rs).flatten()
  • 如果您将轴限制更改为所需的图片限制,那么您的代码会生成相同的图表
  • 您好,感谢 cmets,但更改为 rs = np.array(rs).flatten() 并没有帮助,@DavidG 我如何更改上面代码中的限制。我以为我是用代码“rs = np.linspace(0,pi/2,1000)”和“t0 = 0.0”来建立它们的。

标签: python matplotlib scipy


【解决方案1】:

问题中的两个图表是相同的,但是它们都有不同的限制。要更改限制,您需要执行 plt.xlim()plt.ylim()。将它们设置为与期望的结果相同会得到相同的结果。

除了期望的结果之外,还有一个额外的结果,即 y 轴在 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()

这给出了:

【讨论】:

    【解决方案2】:

    不确定我是否理解您的问题,但似乎两个图中的解决方案是相同的,但它们的绘制方式不同。在“一个 C 值的所需解决方案”图中,与 x 轴相比,y 轴被拉伸。在您的“current_solution”中,它们是相等的。

    【讨论】:

      猜你喜欢
      • 2016-04-09
      • 2023-03-31
      • 2015-12-13
      • 2012-02-28
      • 1970-01-01
      • 2022-07-16
      • 1970-01-01
      • 2012-11-14
      相关资源
      最近更新 更多