首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python中的Runge-Kutta方法

Python中的Runge-Kutta方法
EN

Stack Overflow用户
提问于 2015-07-30 08:37:37
回答 2查看 3.6K关注 0票数 0

我用python编写了关于runge方法的代码,但是每次当程序实现任何微积分时,程序都需要微分方程。

这是我的密码:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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]

我该怎么做才能只输入一次微分方程来计算全部呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-07-30 09:14:22

如果我不明白就纠正我。您是否试图获得用户手动输入的表达式,并将其视为函数?我找到了本题,它解释了如何使用渐近解析公式。您可以尝试使用同情修改程序。以这种方式,你应该能够一劳永逸地得到你的方程式。

编辑:如果你的问题只是“如何从输入得到整个公式一次.”您可以尝试使用raw_input()方法。还可以看一下这里

票数 1
EN

Stack Overflow用户

发布于 2015-07-30 09:41:22

您必须将方程输入代码移出函数f(x,y)

请将方程输入到与您要求的所有其他输入相同的块中。

当它处于状态时,您的代码将在每个时间间隔调用函数,因此将在每个时间间隔请求输入。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31718950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档