在 JavaScript 中对指数求和

summing exponents in javascript

本文关键字:指数 求和 JavaScript      更新时间:2023-09-26
var total = 0;
for (x = 1; x < 16; x++) {
    var y = x + 1;
    var singleSum = Math.pow(x, y) + Math.pow(y, x);
    total = total + singleSum;
    document.write(total + "<br>");
}

我想取function(x,y) = x^y + y^x x 从 1 开始,y 从 2 开始,然后找到前 15 次函数调用的总和。我不知道我做错了什么。任何帮助将不胜感激。谢谢。

浮点计算中遇到了精度损失。正确答案的表示精度高于您使用的浮点数的大小。(这有点像政府在计算税款时忽略美分的方式。

以下是 Python 中的计算,使用任意精度算法:

>>> sum(x**(x+1) + (x+1)**x for x in range(1,16))
7910956276398901049L

(末尾的L表示"长"整数。

请注意,正确答案末尾有一个049,而您的答案中缺少该。

我得到的答案是7910956276398901000

没有说预期的答案是什么,但假设它与你得到的问题类似,JavaScript使用IEEE-754双精度(64位(格式表示数字。据我了解,这为您提供了 53 位精度,或 15 到 16 位十进制数字。7910956276398901000,你得到的数字比JavaScript可以处理的数字多,所以你最终得到一个"真实"答案的近似值。

你可以

这样做:

var total = new BigNumber(0);
for (x = 1; x < 16; x++) {
    var singleSum = new BigNumber(x).pow(x+1).add(new BigNumber(x+1).pow(x));
    total = total.add(singleSum);
    document.write(total + "<br>");
}

在 http://jsfromhell.com/classes/bignumber 的帮助下

输出为:

3
20
165
1814
25215
422800
8284753
185549202
4672333603
130609758204
4012046505613
134303337007166
4865394495960599
189626416079163448
7910956276398901049