题目:已知目标函数F(X)=x+20/x,取初始区间[a,b]=[2,10],ε=0.01。分别用0.618法和二次插值法求最优解。
public class Main {
public static void main(String[] args) {
//初始数据
double a=2.0;
double b=10.0;
double miu=0.01;
f_618 h=new f_618(a,b,miu);
h.SuanFa();
}
}
class f_618 {
double a;
double b;
double miu;
double x1;
double x2;
public f_618(double a,double b,double miu){
this.a=a;
this.b=b;
this.miu=miu;
this.x1=0.0;
this.x2=0.0;
}
public void SuanFa() {
int k=0;
fun f=new fun();
while(true) {
k++;
x1=a+0.382*(b-a);
x2=a+0.618*(b-a);
System.out.println("x1:"+x1+"x2:"+x2);
if((b-a)<miu) break;
else {
if(f.F(x1)>f.F(x2)) {
System.out.println("左边f(x1):"+f.F(x1)+"f(x2):"+f.F(x2));
a=x1;
x1=x2;
x2=a+0.618*(b-a);
}
else {
System.out.println("右边f(x1):"+f.F(x1)+"f(x2):"+f.F(x2));
b=x2;
x2=x1;
x1=a+0.382*(b-a);
}
}
System.out.println("迭代了"+k+"次,区间[a,b]=["+a+","+b+"]"+'\n'+"f(a)="+f.F(a)+'\n'+"f(b)="+f.F(b));
}
double f1=f.F(a);
double f2=f.F(b);
System.out.println("迭代了"+k+"次,最优区间[a,b]=["+a+","+b+"]"+'\n'+"f(a)="+f1+"f(b)="+f2);
}
}
class fun {
public double F(double x) {
//目标函数
x=x+(20.0/x);
return x;
}
}
答案
左边f(x1):8.944272678017402f(x2):8.944272608908868
迭代了14次,区间[a,b]=[4.470283049462319,4.479765675814997]
f(a)=8.944272678017402
f(b)=8.944284904571628
x1:4.473905412729042x2:4.476143312548274
迭代了15次,最优区间[a,b]=[4.470283049462319,4.479765675814997]
f(a)=8.944272678017402f(b)=8.944284904571628
参考:https://blog.csdn.net/weixin_49858823/article/details/118915862