⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rootneu.cpp

📁 计算方法程序常微分方程的数值解法课堂讲义
💻 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 + -