0.618法

一种经典的一维搜索方法

用的集合装,实际应该更简单!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package cn.sgnxotsmicf.Demo;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Scanner;
public class Demo_Number {
static double T = 0.618;
static {
System.out.println("======0.618法求解最优化问题======");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Double> Data = new ArrayList<>();
inPut(sc,Data);
}

private static void inPut(Scanner sc,ArrayList<Double> Data) {
System.out.println("请输入允许误差ε:");
double c = sc.nextDouble();
System.out.println("给定搜索左区间a:");
double a = sc.nextInt();
System.out.println("给定搜索右区间b:");
double b = sc.nextInt();
LocalDateTime startTime = LocalDateTime.now();
Init(Data,a,b);
Judge(Data,c);
LocalDateTime endTime = LocalDateTime.now();
System.out.println("迭代时间大约为:"+ChronoUnit.MICROS.between(startTime, endTime)+"微秒");
}

/**
!!!注意:函数在此方法下修改
*/
private static double function(double tempt){
return tempt*tempt-tempt+2;//0.554
}

private static void Init(ArrayList<Double> Data,double a, double b) {
double L = a+(1-T)*(b-a);
double U = a+T*(b-a);
double L1 = function(L);
double U1 = function(U);
Data.add(L);//0
Data.add(U);//1
Data.add(L1);//2
Data.add(U1);//3
Data.add(a);//4
Data.add(b);//5
}

private static void Judge(ArrayList<Double> Data,double c) {
while(true) {
if(Math.abs(Data.get(4)-Data.get(5))>c) {
if(Data.get(2)<Data.get(3)) {
Data.set(5, Data.get(1));//b的值
Data.set(1, Data.get(0));
Data.set(3, Data.get(2));
Data.set(0, Data.get(4)+(1-T)*(Data.get(5)-Data.get(4)));
double tempt = Data.set(0, Data.get(4)+(1-T)*(Data.get(5)-Data.get(4)));
Data.set(2, function(tempt));
}else {
Data.set(4, Data.get(0));//a的值
Data.set(0,Data.get(1));
Data.set(2,Data.get(3));
Data.set(1,Data.get(4)+T*(Data.get(5)-Data.get(4)));
double tempt = Data.set(1,Data.get(4)+T*(Data.get(5)-Data.get(4)));
Data.set(3,function(tempt));
}
}else {
DecimalFormat sc = new DecimalFormat("0.000");
System.out.println("最优解x="+sc.format((Data.get(4)+Data.get(5))/2));
break;
}
}
}
}