将Euler转换为Heun(改进的Euler)

时间:2013-12-05 14:29:56

标签: wolfram-mathematica

我已经在Mathematica中实现了Euler方法。 现在我想将此方法转换为Heun方法(改进的Euler)。

我有这个Euler实现:

a = 2;(*my a parameter*)
b = .01;                 (*my b parameter*)
x = 0;                   (*starting x value*)
p = 1;                   (*starting p value*)
t = 1;                   (*step size t*)
f[p_] := a p - b p^2;    (*my function*)
f[0] = 1;
eulertable = {};         (*build table (x,p).n steps in loop*)
For[n = 1, 
 n <= 21, n++, 
  AppendTo[eulertable, {x, p}];
  p = p + t f[p];
  x = x + t;]

现在我想用Heun方法实现它。我已经有了Heun方法的实现。

heun[f_, {x_, x0_, xn_}, {y_, y0_}, steps_] :=
 Block[{ xold = x0, yold = y0, sollist = {{x0, y0}}, x, y, h },
 h = N[(xn - x0) / steps]; 
 Do[ xnew = xold + h;
     k1 = h * (f /. {x -> xold, y -> yold});
     k2 = h * (f /. {x -> xold + h, y -> yold + k1});
     ynew = yold + .5 * (k1 + k2);
     sollist = Append[sollist, {xnew, ynew}];
     xold = xnew;
     yold = ynew,
 {steps}
 ];
 Return[sollist]
 ] 

但我需要转换此方法以使输入像我的Euler方法一样。所以我必须转换Heun方法,我有参数a,b,x,t,p,f []。

由于我是Mathematica的新手,我在转换方法时遇到了问题。

1 个答案:

答案 0 :(得分:0)

为什么要放f[0]=1

替换

p = p + t f[p];
x = x + t;

p1 = p + t f[p];
p2 = p + t f[p1];
p = (p1+p2)/2;
x = x + t;

您的步长对于参数值来说相当大。