簡單題-不用庫函數,求解一個數位平方根

來源:互聯網
上載者:User

題目:

如標題所示,不用平方根庫函數,求解一個數位平方根。

分析:

這個問題有兩個思路:

思路1:採用二分的方式(無處不在的二分),上界初始化為數字本身,下界初始化為1,這樣用二分,判斷中間數位平方和目標數字比較,再修改上界和下界,直到小於一定的閾值。

思路2:採用牛頓法(數值分析中提到),採用微分的方式,從初始點開始,每次迭代,微分求解切線,然後求解切線和x軸的交點,再以這個交點作為起點,迭代進行。比如求解24,那麼寫出函數:

f(x) = x^2 - 24

我們目標就是求解這個函數的根,函數一階導數是:

f'(x) = 2*x

起始點可以選擇x0 = 24,通過求解,可以得到下一個迭代點的公式為:

x1 = -f(x0) / f'(x0) + x0

這樣迭代下去,直到最後小於一定的閾值。

演算法代碼如下:

/* * square.cpp * *  Created on: 2012-10-4 *      Author: happier */#include <iostream>#include <algorithm>#include <cstdlib>using namespace std;#define E 0.001//精度設定/* * 二分法求解 */double bSearch(double number, int *count){//int count = 0;double start = 1.0;double end = number;while(true){(*count)++;double mid = (start + end) / 2;if(mid * mid - number <= E && mid * mid - number >= -E)return mid;if(mid*mid - number > E)end = mid;elsestart = mid;}return 0;}/* * 牛頓法求解 */double newton(double number, int *count){double x0 = number;double x1;while(true){(*count)++;x1 = -(x0*x0 - number) / (2 * x0) + x0;if(x1 * x1 - number <= E && x1 * x1 - number >= -E)return x1;x0 = x1;}return 0;}int main(){int count = 0;//統計迭代次數cout << "Please input the number::" << endl;double number;cin >> number;cout << bSearch(number, &count) <<endl;cout << count <<endl;count = 0;cout << newton(number, &count) <<endl;cout << count <<endl;return 0;}


總結:

通過運行發現,牛頓法的求解速度要比二分法快很多,例如求解30000,牛頓法只要11次迭代,可以達到0.001精度,但是二分法需要33次,所以數值分析普遍採用牛頓法進行求根。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.