題目要求
編程實現,用牛頓法求在區間內的一個實根,要求得到小數點後三位爲精確值的近似
牛頓迭代法簡介
牛頓迭代法又稱爲牛頓-拉弗森方法,實際上是由牛頓、拉弗森各自獨立提出來的。
牛頓-拉弗森方法提出來的思路就是:利用切線是曲線的線性逼近。
圖片演示:(這裏先空着,咕咕咕)
C++代碼實現
#include <bits/stdc++.h>
using namespace std;
const double eps=1e-5;
double f(double x) //函數
{
return x*x*x+4*x*x-10;
}
double df(double x) //導數
{
return 3*x*x+8*x;
}
int main()
{
double x0=1;
while(fabs(f(x0))>eps)
{
x0=-f(x0)/df(x0)+x0;
}
cout<<x0<<endl;
return 0;
}
matlab代碼實現(等我的破神舟返廠回來着)
Python代碼實現
class Newton:
def __init__(self):
self.x=None
self.eps=1e-5
def f(self,x):
return x**3+4*x**2-10
def df(self,x):
return 3*x**2+8*x
def appro(self):
while abs(self.f(self.x))>self.eps :
self.x=-self.f(self.x)/self.df(self.x)+self.x
return self.x
def main():
n = Newton()
n.x=1
print("%.5f"%n.appro())
main()