1
votes

I want to implement Newton-Raphson method in Mathematica.

Here is my code:

f[x] = x^3 - x^2 + 1

MetodaTangente[x0_, eps_] := Block[{p0, p1, dp, k},
   p0 = N[x0];
   p1 = p0;
   dp = 1;
   k = 0;
   While[dp > eps,
    p0 = p1;
    p1 = p0 - f[p0]/f'[p0];
    dp = Abs[p1 - p0];
    k = k + 1;
    ];
   Print[p1];
   ];

k counts how many iterations was there.

However, here's what happens when I run this:

enter image description here

It seems that there's a problem with f. What should I do now?

1
This Mathworld page - mathworld.wolfram.com/NewtonsMethod.html - contains a much more Mathematica-idiomatic implementation of this method. So too, if memory serves, does the Mathematica documentation but I don't have that available right now. - High Performance Mark

1 Answers

3
votes

Define your function like this instead:

f[x_] := x^3 - x^2 + 1
MetodaTangente[-1, .000000000001]

> -0.754878

More info: http://reference.wolfram.com/mathematica/tutorial/DefiningFunctions.html