Метод Рунге-Кутты в Python

Я написал код метода рунге-кутта на питоне, но каждый раз, когда программа реализует какое-либо исчисление, программе требуется дифференциальное уравнение.

это мой код:

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]

Что мне делать, чтобы ввести дифференциальное уравнение только один раз, чтобы программа рассчитала все?


person Jeff    schedule 30.07.2015    source источник


Ответы (2)


Поправьте меня, если я не понял. Вы пытаетесь получить выражение, введенное пользователем вручную, и рассматривать его как функцию? Я нашел этот раздел, где объясняется, как анализировать формулу с помощью sympy. Вы можете попробовать изменить свою программу с помощью sympy. Таким образом, вы сможете раз и навсегда получить свое уравнение.

РЕДАКТИРОВАТЬ: если ваша проблема заключается в том, «как получить всю формулу один раз из ввода ...», вы можете просто попробовать использовать метод raw_input (). Также посмотрите здесь:

person BY0B    schedule 30.07.2015
comment
ну вы должны спросить, это комментарий, а не ответ - person VeKe; 30.07.2015
comment
Я даю два ответа, поэтому не думаю, что ошибаюсь, нажимая кнопку ответа. Кстати, спасибо за конструктивный комментарий. - person BY0B; 30.07.2015
comment
Спасибо большое, не подумал использовать sympy. - person Jeff; 30.07.2015

Вы должны переместить код ввода уравнения из функции f(x,y)

Попросите ввести уравнения в тот же блок, что и все остальные входные данные.

В его нынешнем виде ваш код вызывает функцию в каждом временном интервале, поэтому будет запрашивать ввод в каждом временном интервале.

person DrBwts    schedule 30.07.2015