0.618法
import java.util.*;
public class Main {
public static void main(String[] args) {
// 左右边界,可自定义
// eps 精度大小
double a = -3, b = 5, eps = 0.2;
double t = 0.618;
double x2 = a + t * (b - a), x1 = a + b - x2;
double fx1 = cal(x1), fx2 = cal(x2);
while (b - a > eps) {
if (fx1 >= fx2) {
a = x1;
x1 = x2;
fx1 = fx2;
x2 = a + b - x1;
fx2 = cal(x2);
} else {
b = x2;
x2 = x1;
fx2 = fx1;
x1 = a + b - x2;
fx1 = cal(x1);
}
}
System.out.println((a + b) / 2);
}
// 函数计算方法
static double cal(double x) {
return x * x + x * 2;
}
}
三大原则:
- 去坏留好
- 对称
- 等比收缩
优缺点:
优点:不要求函数可微,且每次迭代只需要计算一个函数值,计算量小,程序简单
缺点:收敛速度慢