- 阅读权限
- 255
- 威望
- 0 级
- 论坛币
- 1948 个
- 通用积分
- 8.7693
- 学术水平
- 159 点
- 热心指数
- 165 点
- 信用等级
- 144 点
- 经验
- 6203 点
- 帖子
- 754
- 精华
- 0
- 在线时间
- 666 小时
- 注册时间
- 2010-10-24
- 最后登录
- 2024-7-17
|
沙发
马甲1号
发表于 2016-5-8 04:11:12
- ##runge-kutta
- Runge_Kutta <- function(f,b,c,A,y0,x0,h,N){
- stopifnot( length(c)== nrow(A))
- x=x0
- y=y0
- message(sprintf( 'initial condition, x=%f, y=%f',x,y))
- for(n in 1:N){
- #cal k1
- K=h*f(x,y)
- #cal k2...kN
- for(s in 2:length(c)){
- k= h*f(x+c[s]*h, y+ A[s, 1:(s-1) ]*K )
- K=c(K,k)
- }
- #update x,y
- y=y+ sum(b*k)
- x=x+ h
- message(sprintf( 'iteration %d, x=%f, y=%f',n,x,y))
- }
- yN=y
- return(yN)
- }
- b= c(1/6,1/3,1/3,1/6)
- c= c(0, 1/2,1/2,1)
- A= matrix(c(0,0,0,0,1/2,0,0,0,0,1/2,0,0,0,0,1,0), nrow=4,ncol=4,byrow=T)
- f=function(x,y){-2*y*x^2}
- yN=Runge_Kutta(f,b,c,A,y0=1,x0=0,h=.001,N=1000)
- yE=exp(-2/3* 1^3)
- message(sprintf('Runge_Kutta method result at x=1 is %f; exactly result is %f.',yN,yE))
复制代码
|
|