Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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++:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading