-1

我正在编写一个 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.1u[0] = 0v = 0.5

4

1 回答 1

0

我不确定你在问什么,也许这很有用:

# example u and v
u = [1.003, 1.002, 1.001]
v = [0, 0, 0]

for i, (uapprox, vapprox) in enumerate(zip(u, v)):
    print "on iteration", i, "u ~", uapprox, "and v ~", vapprox

输出:

on iteration 0 u ~ 1.003 and v ~ 0
on iteration 1 u ~ 1.002 and v ~ 0
on iteration 2 u ~ 1.001 and v ~ 0
于 2015-08-02T13:10:23.153 回答