Re: FindRoot inside a loop
- To: mathgroup at smc.vnet.net
- Subject: [mg23329] Re: [mg23278] FindRoot inside a loop
- From: Carl Woll <carlw at u.washington.edu>
- Date: Tue, 2 May 2000 00:43:11 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
Carlos,
Rather than using FindRoot for each different value of x, it may be
simpler to
convert your parametric equation into an ODE and solve the ODE. For
example, if
you have the equation
f[x,y]==0
and you want to solve this equation for different values of x, I would
solve
the ODE
D[f[x,y[x],x]==0
with some suitable starting point. To be more concrete, suppose
In[53]:=
f[x_, y_] := y E^-x - x
Then obviously x=0, y=0 is a solution. To find solutions for other
values of x,
we use NDSolve:
In[54]:=
Clear[y]
NDSolve[{D[f[x, y[x]], x] == 0, y[0] == 0}, y, {x, 0, 1}] /. Rule -> Set
Out[55]=
{{InterpolatingFunction[{{0., 1.}}, <>]}}
We're done. Now, y is the function you want. For example,
In[56]:=
y[0.5]
f[0.5, y[0.5]]
Out[56]=
0.824363
Out[57]=
-6
1.57464 10
Since I chose a particularly simple function, it turns out the exact
solution is
y[x]=x E^x
So, comparing, we have
In[58]:=
0.5 E^0.5
Out[58]=
0.824361
If you want to improve the accuracy of this solution, just increase the
AccuracyGoal and PrecisionGoal in the NDSolve function.
You can plot
Plot[f[x,y[x]],{x,0,1}]
and see that f is close to zero (within ~10^-6 over the whole range).
Carl Woll
"Calle-1, Carlos" wrote:
> I am trying to solve a parametric equation for different values of x.
I
> would like to plot the solutions as a function of x. I set up a loop
(old
> habits from my grad school days programming in FORTRAN). Since
FindRoot has
> the HoldAll attribute, I am using Evaluate. The Print{%] statement
inside
> the loop outputs -graphics-, which were produced right before the loop
> starts. The last % correctly outputs the last value computed.
>
> Clearly, I don't know enough about how Mathematica stores values and
> therefore can't extract them. Do I define a function to store the
values?
> But what are the values called when FindRoot solves the equation at
each
> iteration?
>
> <<...>>
>
> Thanks,
>
> Carlos Calle