我正在编写一个 python 程序来解决给定两个初始条件的一阶微分方程的 2x2 系统。我的代码:
from math import *
import numpy as np
np.set_printoptions(precision=6) ## control numpy's decimal output :)
form1 = raw_input('Enter the 1st function of u & v only >> ')
form2 = raw_input('Enter the 2nd function of u & v only >> ')
start = input("Enter the lower limit of the interval >> ")
stop = input("Enter the upper limit of the interval >> ")
h = input("Using step size? ")
N = int(np.round((stop - start)/h, decimals = 4)) ##calculate the number of times to iterate
## np.round fixes a python bug returning 2.99999997 instead of
## 3 which reduced the number of times iterated by -1
k = np.zeros((2, 4))
u = np.zeros((N +1,)) ## fill our u's first with N+1 0's
v = np.zeros((N +1,)) ## fill our v's first with N+1 0's
u[0] = input("Give me an initial value for u'>> ")
v[0] = input("Give me the second initial value for v' >> ")
t = np.arange(start, stop + h, h)
def f1(t, u, v):
return eval(form1)
def f2(t, u, v):
return eval(form2)
##for u now
def trialu():
for j in range(0, N):
k[0, 0] = h * f1(t[j], u[j], v[j])
k[1, 0] = h * f2(t[j], u[j], v[j])
k[0, 1] = h * f1(t[j] + h/2, u[j] + 0.5*k[0, 0], v[j] + 0.5*k[1, 0])
k[1, 1] = h * f2(t[j] + h/2, u[j] + 0.5*k[0, 0], v[j] + 0.5*k[1, 0])
k[0, 2] = h * f1(t[j] + h/2, u[j] + 0.5*k[0, 1], v[j] + 0.5*k[1, 1])
k[1, 2] = h * f2(t[j] + h/2, u[j] + 0.5*k[0, 1], v[j] + 0.5*k[1, 1])
k[0, 3] = h * f1(t[j], u[j] + k[0, 2], v[j] + k[1, 2])
k[1, 3] = h * f2(t[j], u[j] + k[0, 2], v[j] + k[1, 2])
u[j+1] = u[j] + (k[0, 0] + 2*k[0, 1] + 2*k[0, 2] + k[0, 3])/6
v[j+1] = v[j] + (k[1, 0] + 2*k[1, 1] + 2*k[1, 2] + k[1, 3])/6
return u
我知道我可以return (u, v)
,但我想以print "u ~ ", u
不同的方式v
在另一条线上,但似乎我只需要重复 trialu 来返回 v,有没有更好的方法?不重复def trialu()
?我还想分别为 j = 1, 2, ... 打印 k?
一个例子是通过使用和的步长来解决u' = -3*u + 2*v
和。v' = 3*u - 4*v
[0,0.4]
h = 0.1
u[0] = 0
v = 0.5