我无法将initial_guess_1和initial_guess_2的更新值传回GoldenSectionSearch方法(我试图让方法调用自己,直到满足与“if”相关的终止条件)。我自己解决这个问题的尝试受到了我在这里发现的影响:
http://www.java-tutorial.com/java-tutorial/java-classes-methods/java-call-reference/
在尝试将更新的值传回方法时,我仍然无法弄清楚我做错了什么。我做错了什么,我该如何解决?我是编程新手,希望把事情分解成最小,最容易理解的术语。
public static double GoldenSectionSearch(double x_1, double x_2, double initial_guess_1,double initial_guess_2 ,double gradient_x, double gradient_y, double a,double a_0,double a_1,double a_2,double b_0,double b_1,double p,double N){
//Stuff
if(Math.abs((100*(x_2 - x_1*x_1)*(x_2 - x_1*x_1) + (1- x_1)*(1- x_1)) - (100*(initial_guess_2 - initial_guess_1*initial_guess_1)*(initial_guess_2 - initial_guess_1*initial_guess_1) + (1- initial_guess_1)*(1- initial_guess_1)) )/Math.abs(1+(100*(initial_guess_2 - initial_guess_1*initial_guess_1)*(initial_guess_2 - initial_guess_1*initial_guess_1) + (1- initial_guess_1)*(1- initial_guess_1))) >=0.50*Math.pow(10,-6)){
initial_guess_1=x_1;
initial_guess_2=x_2;
//Double Boxed_a = new Double(a);
Double Boxed_initial_guess_1 = new Double(initial_guess_1);
Double Boxed_initial_guess_2 = new Double(initial_guess_2);
initial_guess_1.GoldenSectionSearch(initial_guess_1);
initial_guess_2.GoldenSectionSearch(initial_guess_2);
gradient_x = (400*initial_guess_1*(initial_guess_1*initial_guess_1 - initial_guess_2) + 2*(initial_guess_1 -1));
gradient_y = (200*(initial_guess_2 - initial_guess_1*initial_guess_1));
GoldenSectionSearch(initial_guess_1,initial_guess_2,x_1, x_2, gradient_x, gradient_y, a, a_0, a_1, a_2, b_0, b_1, p,N);
} else{
double f_x=(100*(x_2 - x_1*x_1)*(x_2 - x_1*x_1) + (1- x_1)*(1- x_1));
System.out.print("alpha = " + a + " " + "x_1 = " + x_1 + " " + "x_2 = " + x_2 + " " + "f_x = " + f_x);
}
// Double Boxed_a = new Double(a);
return x_2;
}
答案 0 :(得分:0)
您无法修改基元。您必须使用getter / setter创建包装类
public class MyWrapperObject {
private double x_1;
private double x_2;
private double initial_guess_1;
private double initial_guess_2;
private double gradient_x;
private double gradient_y;
private double a;
private double a_0;
private double a_1;
private double a_2;
private double b_0;
private double b_1;
private double p;
private double N;
public double getX_1() {
return x_1;
}
public void setX_1(double x_1) {
this.x_1 = x_1;
}
/* The rest of getters/setters */
}
将其传递给您的方法并像
一样使用它public static double GoldenSectionSearch(MyWrapperObject obj){
// ...
double initial_guess_1 = obj.get_initial_guess_1();
double initial_guess_2 = obj.get_initial_guess_2();
obj.setGradient_x(400*initial_guess_1*(initial_guess_1*initial_guess_1 - initial_guess_2) + 2*(initial_guess_1 -1));
// ...
}
此处还有一个问题,即java是传递引用还是值传递https://stackoverflow.com/a/40523/2022162