javascript - 求解未知指数
问题描述
我试图让一个函数创建一个指数增加的数字列表,其中数字的总和等于某个最大值。
例如:
/*
* 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
解决方案
试试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);
推荐阅读
- python - 如何将 datetime.now().isoformat() 添加到 NamedTuple 的 __init__?
- javascript - 如何在 JavaScript 中从外部范围访问变量
- python - 如何在不公开提供凭据的情况下向 Scrapy Cloud 提供 API 凭据?
- c# - 参考其他表格的 ASP.NET Formview 下拉列表
- java - 从 TD/B HTML 标签中提取文本 ,xpath="//table[@class='table']/tbody/tr[1]/td
- react-native - 使用 react native fetch blob 下载图像文件
- javascript - 允许 JS 使用 insertAdjacentHTML (Plain JS) 在 AJAX .responseText 中运行的工作方法
- javascript - 打印服务器响应
- angularjs - 在AngularJS列表的顶部选中复选框对项目进行排序
- python - Matplotlib 数据框饼图绘图与我的 0% 标签重叠