       Re: Coding for Mathematica

• To: mathgroup at smc.vnet.net
• Subject: [mg100601] Re: [mg100555] Coding for Mathematica
• From: DrMajorBob <btreat1 at austin.rr.com>
• Date: Tue, 9 Jun 2009 03:54:19 -0400 (EDT)
• References: <200906080604.CAA19997@smc.vnet.net>

```The results here are:

f[x_] := x^2 - 2
x = 1.0
For[n = 1, n < 10, n++, {x[n + 1] = x[n] - f[x[n]]/f'[x[n]];
Print[n + 1, "  ", N[x[n + 1], 10]];}]
Plot[f[x], {x, 0, 2}]

1.

2  1.5

3  1.41667

4  1.41422

5  1.41421

6  1.41421

7  1.41421

8  1.41421

9  1.41421

10  1.41421

(plus the graph)

And that's exactly what your code asked for. Other code options include:

Solve[f@x == 0, x]

{{x -> -Sqrt}, {x -> Sqrt}}

NSolve[f@x == 0, x]
{{x -> -1.4142135623730951`}, {x -> 1.414213562373095`}}

FindRoot[f@x, {x, 1}]

{x -> 1.41421}

FixedPointList[# - f[#]/f'[#] &, 1.]

{1., 1.5, 1.41667, 1.41422, 1.41421, 1.41421, 1.41421}

but not this, which doesn't terminate:

FixedPointList[# - f[#]/f'[#] &, 1]

That's because starting with 1, and EXACT number, causes all the
iterations to use exact arithmetic as well, so the stopping rule never
activates. A different sort of failure SOMETIMES occurs if you start with
an "arbitrary precision" version of 1, if precision is lost at each
iteration.

To illustrate what happens, I'll limit the number of iterations:

FixedPointList[# - f[#]/f'[#] &, 1, 7]

{1, 3/2, 17/12, 577/408, 665857/470832, 886731088897/627013566048, \
1572584048032918633353217/1111984844349868137938112, \
4946041176255201878775086487573351061418968498177/\
3497379255757941172020851852070562919437964212608}

or

Precision /@ FixedPointList[# - f[#]/f'[#] &, SetPrecision[1., 10]]

{10., 9.77815, 9.4404, 9.13824, 8.83721, 8.53618}

Loss of precision wasn't severe enough to prevent convergence, in this
case.

Bobby

On Mon, 08 Jun 2009 01:04:39 -0500, FAQneeds <thegodfather7769 at aol.com>
wrote:

> Im a first time user of Mathematica. So im trying to put in a command
> related to Newton's Method. I would just like to know if once im done
> typing this command in am i suppose to see the results immediately or do
> i have go to something in the program to see the results of my command.
> Here is the Code please can anyone tell me what im doing wrong i will be
> really grateful:
>
> In :=(*Newton's Method*)
> In := f[x_] := x^2 - 2
> In := x = 1.0
> In := For[n = 1, n < 10, n++,
>   {x[n + 1] = x[n] - f[x[n]]/f'[x[n]];
>    Print[n + 1, "  ", N[x[n + 1], 10]];}]
> In := Plot[f[x], {x, 0, 2}]
>

--
DrMajorBob at bigfoot.com

```

• Prev by Date: Re: Re: Re: directionfields from StreamPlot
• Next by Date: Re: Re: Re: directionfields from StreamPlot
• Previous by thread: Coding for Mathematica
• Next by thread: Re: Coding for Mathematica