在mathematica中,如何将初始条件作为ndsolve中的变量?

时间:2010-12-07 21:24:58

标签: wolfram-mathematica

我想要这样的东西

w[w1_] := 
 NDSolve[{y''[x] + y[x] == 2, y[0] == w1, y'[0] == 0}, y, {x, 0, 30}]

这看起来好像效果更好但我觉得我错过了smtn

w := NDSolve[{y''[x] + y[x] == 2, y[0] == w1, y'[0] == 0}, 
  y, {x, 0, 30}]
w2 = Table[y[x] /. w, {w1, 0.0, 1.0, 0.5}]

因为当我尝试制作一张桌子时,它不起作用:

Table[Evaluate[y[x] /. w2], {x, 10, 30, 10}]

我收到错误:

ReplaceAll::reps: {<<1>>[x]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>
ps:有更好的地方可以提出这样的问题吗? mathematica没有支持的论坛,只有mathGroup电子邮件列表。如果stackoverflow会有更具体的mathematica标签,例如,简化,ndsolve,绘图操作,那将是很好的

2 个答案:

答案 0 :(得分:4)

有很多方法可以做到这一点。一个是:

w[w1_] :=  NDSolve[{y''[x] + y[x] == 2, 
                     y'[0] == 0},      y[0] == w1,
                      y[x], {x, 0, 30}];

Table[Table[{w1,x,y[x] /. w[w1]}, {w1, 0., 1.0, 0.5}]/. x -> u, {u, 10, 30, 10}] 

输出:

{{{0., 10, {3.67814}}, {0.5, 10, {3.25861}}, {1.,10, {2.83907}}}, 
 {{0., 20, {1.18384}}, {0.5, 20, {1.38788}}, {1.,20, {1.59192}}}, 
 {{0., 30, {1.6915}},  {0.5, 30, {1.76862}}, {1.,30, {1.84575}}}}

答案 1 :(得分:1)

我看到你已经选择了一个答案,但我想把这个解决方案用于线性方程族。具体来说,这是对Lotka-Volterra的微小变化进行建模。

(*Put everything in a module to scope x and y correctly.*)
Module[{x, y},

 (*Build a function to wrap NDSolve, and pass it
              the initial conditions and range.*)
 soln[iCond_, tRange_, scenario_] :=
  NDSolve[{
    x'[t] == -scenario[[1]] x[t] + scenario[[2]] x[t]*y[t],
    y'[t] == (scenario[[3]] - scenario[[4]]*y[t]) - 
      scenario[[5]] x[t]*y[t],
    x[0] == iCond[[1]],
    y[0] == iCond[[2]]
    },
   {x[t], y[t]},
   {t, tRange[[1]], tRange[[2]]}
   ];

 (*Build a plot generator*)
 GeneratePlot[{iCond_, tRange_, scen_, 
    window_}] :=
  (*Find a way to catch errors and perturb iCond*)     
  ParametricPlot[
   Evaluate[{x[t], y[t]} /. soln[iCond, tRange, scen]],
   {t, tRange[[1]], tRange[[2]]},
   PlotRange -> window,
   PlotStyle -> Thin, LabelStyle -> Medium
   ];

 (*Call the plot generator with different starting conditions*)
 graph[scenario_, tRange_, window_, points_] :=
  {plots = {};
   istep = (window[[1, 2]] - window[[1, 1]])/(points[[1]]+1);
   jstep = (window[[2, 2]] - window[[2, 1]])/(points[[2]]+1);
   Do[Do[
     AppendTo[plots, {{i, j}, tRange, scenario, window}]
     , {j, window[[2, 1]] + jstep, window[[2, 2]] - jstep, jstep}
     ], {i, window[[1, 1]] + istep, window[[1, 2]] - istep, istep}];
   Map[GeneratePlot, plots]
   }
 ]
]

然后我们可以使用Animate(或表格,但动画非常棒)

tRange = {0, 4};
window = {{0, 8}, {0, 6}};
points = {5, 5}
Animate[Show[graph[{3, 1, 8, 2, 0.5},
      {0, t}, window, points]], {t, 0.01, 5},
      AnimationRunning -> False]