【Machine Learning实验】牛顿迭代法

牛顿迭代法可以用来求取函数的零点,具体参见百度百科吧。。。

 

实验:求取一元三次方程的零点

 

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int Solve(double *para);
double NewtonIteration(double theta,double *para);

#define ITER_MAX 1000

int main(int argc,char *argv[])
{
	//This program is to tackle the cubic equation.	
	if(argc!=5)
	{
		printf("Error:input parameters must be 4.\n");
		return 0;
	}
	double parameters[4];
	for(int i=0;i<4;i++)
		parameters[i]=atof(argv[i+1]);
	printf("Equation:%f*x^3+%f*x^2+%f*x+%f\n",parameters[0],parameters[1],parameters[2],parameters[3]);
	Solve(parameters);
	return 1;
}

int Solve(double *para)
{
	double theta=100;	//initial
	for(int i=0;i<ITER_MAX;i++)
	{	
		//Newton Iteration
		theta=NewtonIteration(theta,para);
	}
	printf("Answer:%f\n",theta);
	return 1;
}

double NewtonIteration(double theta,double *para)
{
	double ftheta,fthetaDiff;
	ftheta=pow(theta,3)*para[0]+pow(theta,2)*para[1]+theta*para[2]+para[3];
	fthetaDiff=pow(theta,2)*para[0]*3+pow(theta,1)*para[1]*2+para[2];
	theta-=ftheta/fthetaDiff;
	return theta;
}


结果:

输入:

4 3 2 1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值