python – 用SciPy数字解决ODE问题
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 用SciPy数字解决ODE问题,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1554字,纯文字阅读大概需要3分钟。
内容图文
![python – 用SciPy数字解决ODE问题](/upload/InfoBanner/zyjiaocheng/809/2a95194c834e4d99ae66d8631ae6888a.jpg)
我坚持将scipy.integrate.odeint应用于以下非常简单的ODE:
y(t)/dt = y(t) + t^2 and y(0) = 0
由SciPy计算的解决方案不正确(很可能b / c我在这里混淆了一些东西) – 特别是解决方案不符合初始条件.
import numpy as np
import scipy.integrate
import matplotlib.pyplot as plt
import math
# the definition of the ODE equation
def f(y,t):
return [t**2 + y[0]]
# computing the solution
ts = np.linspace(-3,3,1000)
res = scipy.integrate.odeint(f, [0], ts)
# the solution computed by WolframAlpha [1]
def y(t):
return -t**2 - 2*t + 2*math.exp(t) - 2
fig = plt.figure(1, figsize=(8,8))
ax1 = fig.add_subplot(211)
ax1.plot(ts, res[:,0])
ax1.text(0.5, 0.95,'SciPy solution', ha='center', va='top',
transform = ax1.transAxes)
ax1 = fig.add_subplot(212)
ax1.plot(ts, np.vectorize(y)(ts))
ax1.text(0.5, 0.95,'WolframAlpha solution', ha='center', va='top',
transform = ax1.transAxes)
plt.show()
1:WolframAlpha: “solve dy(t)/dt = t^2 + y(t), y(0) = 0”
哪里是我的错误?
解决方法:
你的scipy代码解决了微分方程,初始条件为y(-3)= 0,而不是y(0)= 0. odeint的y0参数是t参数中第一次给出的值.
在y(0)= 0的区间[-3,3]上解决此问题的一种方法是调用odeint两次,如下所示:
In [81]: from scipy.integrate import odeint
In [82]: def f(y,t):
....: return [t**2 + y[0]]
....:
In [83]: tneg = np.linspace(0, -3, 500)
In [84]: tpos = np.linspace(0, 3, 500)
In [85]: sol_neg = odeint(f, [0], tneg)
In [86]: sol_pos = odeint(f, [0], tpos)
In [87]: plot(tneg, sol_neg)
Out[87]: [<matplotlib.lines.Line2D at 0x10f890d90>]
In [88]: plot(tpos, sol_pos)
Out[88]: [<matplotlib.lines.Line2D at 0x107a43cd0>]
In [89]: grid(True)
这创造了
内容总结
以上是互联网集市为您收集整理的python – 用SciPy数字解决ODE问题全部内容,希望文章能够帮你解决python – 用SciPy数字解决ODE问题所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。