Search code examples
c++pascalnewtons-method

Newton-Raphson in Pascal, not very good results


I implemented Newton-Raphson metohd in Pascal. It's strange because the same code in C++ gives good results (for 9 it's 3) but in Pascal for 9 it's 3.25, Why so?

Pascal:

Program NewtonRaphsonIter(output);

{$mode objFPC}

function newton_raphson_iter(a: real; p: real; eps: real; max_i: integer) : real;
var
    x: real;
    i: integer;
begin
    x := a / 2.0;
    i := 0;
    
    repeat
        x := (x + a / x) / 2.0;
        i := i + 1;
        if (x * x = a) then break;
        if (i >= max_i) then break; 
    until abs(x - a / x) > eps;
    result := x;

end;

var
    sqroot: real;
begin
  
  sqroot := newton_raphson_iter(9, 0.001, 0.0000001, 10);
  writeln(sqroot);
  
end.

C++:

#include <iostream>
#include <cmath>
using namespace std;

double sqroot(double num)
{
    double x=num/2;
    while(fabs(x-num/x)>0.000001)
    {
        x=(x+num/x)/2;
        if(x*x==num) break;
    }
    return x;
}

int main()
{
    cout << sqroot(9.0);

    return 0;
}

Solution

  • repeat ... until C; loop terminates when the expression C evaluates to true. In your code, after the first iteration abs(x - a / x) > eps is true, so the loop terminates.

    The termination condition should be inverted:

    until abs(x - a / x) <= eps;
    

    Online demo