var L = 0.001;
var V;
function f(x){
return x*(x+2);
}
function goldenSection(a,b,x1,x2){
var y1 = f(x1),
y2 = f(x2);
if (Math.abs(b - a) < L) {
V = (y1 < y2)? x1 : x2;
// console.log(V);
return V;
}else if (y1 > y2) {
goldenSection(x1, b, x2, x1+0.618*(b-x1));
}else if (y1 <= y2) {
goldenSection(a, x2, a+0.382*(x2-a), x1);
}
}
var a = -3,
b = 5,
x1 = a + 0.382 * (b-a),
x2 = a + 0.618 * (b-a),
x = goldenSection(a,b,x1,x2),
y = f(x);
console.log(V); // 这里能输出
console.log(x); // 但是这里为什么输出不了啊。
为什么输出不了,这个设计JS中的什么知识点。跪求大神指点。晕了。
已解决,也是就是else 中没有返回。
改成如下解决。
var L = 0.001;
function f(x){
return x*(x+2);
}
function goldenSection(a,b,x1,x2){
var y1 = f(x1),
y2 = f(x2),
value;
if (Math.abs(b - a) < L) {
value = (y1 < y2)? x1 : x2;
return value;
}else if (y1 > y2) {
value = goldenSection(x1, b, x2, x1+0.618*(b-x1));
}else if (y1 <= y2) {
value = goldenSection(a, x2, a+0.382*(x2-a), x1);
}
return value;
}
var a = -3,
b = 5,
x1 = a + 0.382 * (b-a),
x2 = a + 0.618 * (b-a),
x = goldenSection(a,b,x1,x2),
y = f(x);
console.log(x);