牛顿-拉夫森在帕斯卡,结果不是很好 [英] Newton-Raphson in Pascal, not very good results

查看:0
本文介绍了牛顿-拉夫森在帕斯卡,结果不是很好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Pascal语言实现了牛顿-拉夫森算法。这很奇怪,因为同样的代码在C++中会产生很好的结果(9的结果是3),但在Pascal中9的结果是3.25,为什么呢?

帕斯卡:

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;
}

推荐答案

repeat ... until C;当表达式C的计算结果为真时,循环终止。在您的代码中,在第一次迭代后abs(x - a / x) > eps为True,因此循环终止。

终止条件应颠倒:

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

Online demo

这篇关于牛顿-拉夫森在帕斯卡,结果不是很好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆