我有一個函式 f(x)。我想計算 x 其中 f(x) = max。我怎樣才能在腳本中做到這一點?
鑒于:x 是一個正數,f(x) 可以是正數或負數。我想從 x = 1 開始。如果 f(1) 已經是負數,我就不再感興趣了。隨著 x 的增加,f(x) 也會回傳增加的值,直到達到峰值,然后 f(x) 減小。峰頂的x是我感興趣的。
編輯:好的,到目前為止我嘗試過的:
我嘗試從 x = 1 開始,然后 x * = 2。如果 f(x) 小于最后一個結果,我將 x 設定回 x/4。
示例:f(16) = 9、f(32) = 11、f(64) = 10。峰值可以在 x=16 和 x=64 之間。所以我的新起點是 f(16)。從那以后,我想以類似的方式繼續,但我找不到演算法。
這是我到目前為止所得到的:
let x = 1
let lasty = 0
let holder = 1
while (iteration < 20) {
let y = myFunction(x)
if(y < lasty ) {
x = x / 4
holder = 1
}
x = holder * 2
holder = 1
lasty = y
}
EDIT2:我的改進版本效果很好,但肯定不完美:
let x = 1
let lasty = 0
let iteration = 0
let previousX = 1
let lastX = 1
let step = 2
let maxY = -Infinity
let bestX = 0
while (iteration < 20) {
let y = myFunction(x)
if (y < 0 && iteration == 1) break
if(y > maxY) {
maxY = y
bestX = x
}
if (y < lasty) {
x = previousX
step *= 0.8
lasty = 0
} else {
previousX = lastX
lastX = x
x = x * step
lasty = y
}
}
if(bestX > 0) {
console.log(`Got best x: ${bestX}`)
}
uj5u.com熱心網友回復:
假設您想最大化 y,您可以只存盤 xy 最高的 x 和 y 值:
let highestX = 1; // this is just the corresponding x value for the highest y
let highestY = -Infinity;
let x = 1
let lasty = 0
let holder = 1
while (iteration < 20) {
let y = myFunction(x);
// code for storing the highest y and corresponding x
if (y > highestY) {
highestY = y;
highestX = x;
}
if(y < lasty ) {
x = x / 4
holder = 1
}
x = holder * 2
holder = 1
lasty = y
}
console.log('f(x) is maximised when x =', highestX);
uj5u.com熱心網友回復:
可以使用遞回函式呼叫來解決。
// array of arguments
const args = [...Array(16).keys()];
// sample function
const sampleFunc = (x) => Math.sin(x);
// recursive function
function getElementWithFuncMaximum(arr, func, index = 0, currValue = 0) {
const currFuncValue = func(arr[index]);
return currFuncValue >= currValue
? getElementWithFuncMaximum(arr, func, index 1, currFuncValue)
: arr[index - 1];
}
console.log(getElementWithFuncMaximum(args, sampleFunc));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/338540.html
標籤:javascript 算法
下一篇:如何將函式指標模板作為模板引數?
