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

📄 c1.cpp

📁 数值分析最常用的四十种算法
💻 CPP
字号:
//C1
//Solve a function,using Newton Methom

#include <stdio.h>
#include <math.h>
#include <iostream.h>
#include <time.h>

//Original Function
double func(double x)  
{
	return x*x*x+x*x-3*x-3;
}

//Differencial Function
double dfunc(double x)
{
	return 3*x*x+2*x-3;
}

//decide whether a number is approximate enough to 0
int iszero(double x)
{
	if (fabs(x)<1e-7)
	    return 1;
	else
		return 0;
}

//Newton Methom
//Troot:tolerantion of root;Tf:toleration of function
int nmf(double x,double Troot,double Tf,long N,int time)      
{
	double x1;
    if (iszero(dfunc(x))==0    && 	 N>0    )
	{
		x1=x-func(x)/dfunc(x);
		time++;
		if (fabs(x1-x)<Troot  ||   fabs(func(x1))<Tf)
		{   
			cout<<"The root is: "<<x1<<endl;              //output the root
			cout<<"The error is: "<<fabs(func(x1))<<endl; //output the error
			cout<<"iteration times"<<time;
			return 1;
		}
		else
		{
			nmf(x1,Troot,Tf,N-1,time);
		}
	}
	else
	{
	     cout<<"This methom doesnot work properly.It will return a unkonwn number"<<endl;	
	}
	return 0;
}

void main()
{
	double x=1.5,Troot=1e-7,Tf=1e-7;          //Initilaze node and tolerance
	long N=1000000;       
	clock_t start, finish;                    //Initilaze times
    start = clock();                          // Gets system time 
	nmf(x,Troot,Tf,N,0);       
	finish = clock();                         // Gets system time again 
	cout<<"The methom takes time: "<<(double)(finish - start) / CLOCKS_PER_SEC<<endl;
	cin>>x;
}

//解为x=1.73205
//仅迭代4次,精度达到了7.977e-12,程序执行时间<0.01s
//可见在知道解的大致值的情况下,Newton Methom是相当好的解法

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -