說明:該篇博客源於博主的早些時候的一個csdn博客中的一篇,由於近期使用到了,所以再次作一總結。原文地址
概述
牛頓迭代法(Newton’s method)又稱爲牛頓-拉夫遜(拉弗森)方法(Newton-Raphson method),它是牛頓在17世紀提出的一種在實數域和複數域上近似求解方程的方法。
1. 牛頓迭代公式
設
過點
實際上牛頓迭代法就是將非線性的問題轉化爲線性問題再做處理。將非線性函數在小範圍內用他的一階泰勒級數表示(也就是在某點泰勒展開取低階項)。
2. 使用牛頓迭代公式求解方程
求解步驟:
1. 原函數:
2. 原函數的導函數:
3. 使用牛頓迭代公式
3. 示例
3.1 利用牛頓迭代公式求解平方根
求解平方根也就是求解函數
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
double m,x = 1.0;
cout<<"Please Input a Num:"<<endl;
cin>>m;
if(m < 0)
{
cout<<"Sorry,Input is Illegal"<<endl;
}
else if(m == 0)
{
cout<<"0"<<endl;
}
else
{
while(fabs(m - (x*x)) >= 0.001)
{
x = (x + m/x)/2.0;
cout<<"x="<<x<<"\tm="<<m<<endl; //顯示運算過程
}
cout<<"The result is:"<<x<<endl;
}
system("pause");
}
3.2 另一種求解平方根的高效方法
提到這個算法就不得不說一個神奇的數字 0x5f375a86 。下面的代碼來自於維基百科,關於更多該數字的奇聞可以點擊下面的鏈接查看:
https://en.wikipedia.org/wiki/Fast_inverse_square_root
int sqrt(float x)
{
if(x == 0) return 0;
float result = x;
float xhalf = 0.5f*result;
int i = *(int*)&result;
i = 0x5f375a86- (i>>1);
result = *(float*)&i;
result = result*(1.5f-xhalf*result*result); // Newton step, repeating increases accuracy
result = result*(1.5f-xhalf*result*result);
return 1.0f/result;
}