Search code examples
wolfram-mathematicanewtons-method

Newton-Raphson method in Mathematica


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?


Solution

  • 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