[英]Method of Runge-Kutta in Python
我在python中編寫了有關runge-kutta方法的代碼,但是每次程序實現任何微積分時,程序都需要微分方程。
這是我的代碼:
from math import *
import numpy as np
#Initial Values
n=input("Enter the number of equations n:")
n=int(n)
x=np.array([])
for i in range(0,n):
x0=input("Enter the initial value of x{}:".format(i))
x=np.append(x,[x0])
t=input("Enter the initial value of t:")
tf=input("Enter the final value of t:")
h=input("Enter the time interval h:")
m=int((tf-t)/float(h))
#Definition of differential equations
def f(t,x):
f=np.array([])
for i in range(0,n):
f0=input("Enter the equation f{}:".format(i))
f=np.append(f,[f0])
return f
a=1.0/6
for i in range(0,m):
k1=f(t,x)
k2=f(t+0.5*h,x+0.5*h*k1)
k3=f(t+0.5*h,x+0.5*h*k2)
k4=f(t+h,x+h*k3)
x=x+a*h*(k1+2*(k2+k3)+k4)
t=t+h
print t, x
使用公式dx / dt = x,x(0)= 1,xf = 1,h = 0.1的示例:
Enter the number of equations n:1
Enter the initial value of x0:1
Enter the initial value of t:0
Enter the final value of t:1
Enter the time interval h:0.1
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
1.0 [ 2.71827974]
一旦編程要計算所有的微分方程,我該怎么做才能輸入?
您必須將方程式輸入代碼移出函數f(x,y)
要求將方程式輸入到要輸入所有其他輸入的同一塊中。
就目前而言,您的代碼會在每個時間間隔調用該函數,因此會在每個時間間隔要求輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.