java实现梯度下降算法

/**
 * 梯度下降算法,求解 f(x)=x^4-3x^3+2 最小值
 * 导数为: f'(x)=4x^3-9x^2
 * @author Zealot
 * @date 2015年12月13日
 */
public class GradientDescent {
//	经过计算, we expect that the local minimum occurs at x=9/4

	double x_old = 0;
	static double x_new = 6; // 从 x=6 开始迭代
	double gamma = 0.01; // 每次迭代的步长
	double precision = 0.00001;//误差
	static int iter = 0;//迭代次数
	//目标函数的导数
	private double  derivative(double x) {
		return 4 * Math.pow(x, 3) - 9 *Math.pow(x, 2);
	}
	
	private void getmin() {
		while (Math.abs(x_new - x_old) > precision){
			iter++;
			x_old = x_new;
		    x_new = x_old - gamma * derivative(x_old);
		}
	}
	
	public static void main(String[] args) {
		GradientDescent gd = new GradientDescent();
		gd.getmin();
		System.out.println(iter+": "+x_new);
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值