?? rootneu.cpp
字號:
/////////////////////////////////////////////////////
// 程序5.3 Newton迭代
#include <stdio.h>
#include <conio.h>
#include <math.h>
#define PRECISION 0.0000001 // 精度控制值
#define MAX_Number 10000 // 最多迭代這么多次
// 函數f(x)
// 如果用其它函數,在這里修改
//
float f( float x )
{
return( x * x * x - x - 1 );
}
// 函數 f(x) 的導數 f'(x)
// 如果用其它函數,在這里修改
//
float df( float x )
{
return( 3 * x * x - 1 );
}
// Newton 迭代
void NewtonIterative( )
{
int k;
float x0,x;
// 輸入初始值
printf("\n\nInput Initial Value:\nx0 = ");
scanf("%f",&x);
// 迭代
k = 1;
do{
x0 = x;
x = x0 - f( x0 ) / df( x0 );
printf("\nx%d=%f", k, x );
++k;
}while( fabs(x-x0) > PRECISION && k < MAX_Number );
if( k >= MAX_Number )
{
// 發散
printf("Simple Iterative failed(k=%d)", k );
}
else
{
// 收斂, 輸出結果
printf( "\n\nIterative times k = %d", k );
printf( "\nRoot x=%f", x );
}
}
void main( )
{
// 迭代
NewtonIterative( );
printf("\n\n\007Press any key to quit!\n");
getch();
}
/*
運行結果:(注意,要運行其它例子,請在程序中修改f(x)和df(x))
Input Initial Value:
x0=1
x1=1.500000
x2=1.347826
x3=1.325200
x4=1.324718
x5=1.324718
x6=1.324718
Iterative times k=7
Root x=1.324718
Press any key to quit!
*/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -