首页 > 解决方案 > 求解未知指数

问题描述

我试图让一个函数创建一个指数增加的数字列表,其中数字的总和等于某个最大值。

例如:

/*
* What do I have to raise N by in order for the sum to be 40
*/

(1**x + 2**x + 3**x + 4**x + 5**x) === 40;

/*
* Wolframalpha tells me: x = 1.76445
* But how can I solve with JS.
*/ 
function listOfNumbers(n, maxSum) {
  // implementation
}

var result = listOfNumbers(5, 40);
/*
 * result === [1, 3.397..., 6.947..., 11.542...,  17.111...]
 * 
*/

result.reduce((acc, n) => acc += n) === 40

标签: javascript

解决方案


试试https://en.wikipedia.org/wiki/Bisection_method

TOLERANCE = 1e-5;

let f = x => (1 ** x + 2 ** x + 3 ** x + 4 ** x + 5 ** x - 40);

let
    min = 0,
    max = 1,
    x = 0;

// roughly locate the upper bound

while (f(max) < 0)
    max *= 2;

// repeatedly bisect the interval [min, max]

while (1) {
    x = (min + max) / 2;
    let r = f(x);

    if (Math.abs(r) < TOLERANCE)
        break;

    if (r > 0) {
        max = x
    } else {
        min = x
    }
}

// now, x is a "good enough" approximation of the root

console.log(x);


推荐阅读