迭代法求平方根

來源:互聯網
上載者:User

簡介
  迭代法也稱輾轉法,是一種不斷用變數的舊值遞推新值的過程,跟迭代法相對應的是直接法(或者稱為一次解法),即一次性解決問題。迭代法又分為精確迭代和近似迭代。“二分法”和“牛頓迭代法”屬於近似迭代法。
  迭代演算法是用電腦解決問題的一種基本方法。它利用電腦運算速度快、適合做重複性操作的特點,讓電腦對一組指令(或一定步驟)進行重複執行,在每次執行這組指令(或這些步驟)時,都從變數的原值推出它的一個新值。

/**用迭代法求平方根**/

#include <stdio.h>

int main()
{
    double a, x0, x1;

    printf("Input a = ");
    scanf("%lf", &a);

    if (a < 0.0)
        printf("Error!/n");
    else
    {
        x0 = a/2;  //由於是求平方根,所以置初值為a/2
        x1 = (x0 + a/x0)/2;
        do
        {
            x0 = x1;
            x1 = (x0 + a/x0)/2;  //迭代公式
        } while (fabs(x0-x1) >= 1e-6);
        printf("sqrt(%lf) = %lf/n", a, x1);
    }
}

 

//用牛頓迭代法求下面方程在1.5附近的根。 2x^3-4x^2+3x-6=0

#include <stdio.h>

int main()
{
    double x=1.5, f, df, d;

    do
    {   f = 2*x*x*x - 4*x*x + 3*x -6;
        df = 6*x*x - 8*x + 3;
        d = f/df;  //增值
        x = x - d;
    } while (fabs(d) >= 1e-6);
    printf("%lf/n", x);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.