1

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;
}
Brian Brown
  • 3,873
  • 16
  • 48
  • 79
  • 1
    Please define 'not very good results' and provide some examples. – user438383 Jan 02 '22 at 12:38
  • it's written in the beginning - sqrt(9) = 3.25 – OrenIshShalom Jan 02 '22 at 12:40
  • 1
    *It's strange because the same code in C++* -- It is not the same code. One program is written in Pascal, the other C++. Pascal and C++ are two different languages, with different rules, syntax, etc. Throw away the C++ code and write the Pascal version as if the C++ version doesn't exist. If you did that, then possibly you will find the mistake in the Pascal code. Looking at C++ code to fix a Pascal mistake doesn't make a lot of sense. – PaulMcKenzie Jan 02 '22 at 12:40
  • You're limiting num iterations to 10? – OrenIshShalom Jan 02 '22 at 12:41
  • @OrenIshShalom: Yes, but even without this it's the same. – Brian Brown Jan 02 '22 at 12:47

1 Answers1

5

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

Evg
  • 25,259
  • 5
  • 41
  • 83