3
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>");
}

I want to take function(x,y) = x^y + y^x where x starts at 1 and y starts at 2 then find the sum of the first 15 function calls. I can't figure out what I'm doing wrong. Any help would be appreciated. Thanks.

Tim
  • 14,447
  • 6
  • 40
  • 63
Nic Meiring
  • 882
  • 5
  • 16
  • 33

3 Answers3

2

You are running into loss of precision in your floating point calculations. The correct answer takes more precision to represent than is available in the magnitude of the floating point number you are using. (This is sort of like how the government ignores cents when calculating taxes.)

Here is the calculation in Python, using arbitrary precision arithmetic:

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

(the L at the end denotes a "long" integer.)

Notice how there is a 049 at the end of the correct answer, that is missing in your answer.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • `x**(x+1) + (x+1)**x` == `2 * x**(x+1)`? – Behrang Feb 14 '12 at 05:48
  • 1
    @BehrangSaeedzadeh: I'm pretty sure that's not true, since for example `2**3 != 3**2`. – Greg Hewgill Feb 14 '12 at 05:49
  • @GregHewgill Thanks for the explanation. That is the correct answer. Any idea how I would be able to solve this in JavaScript or do I just have to accept the level of accuracy it allows? – Nic Meiring Feb 14 '12 at 06:04
  • @NicMeiring: Javascript by itself isn't capable of giving you the exact answer to something like `15**16`. However, there exist "big integer" libraries for Javascript. See [Javascript summing large integers](http://stackoverflow.com/questions/4557509/javascript-summing-large-integers) for suggestions. – Greg Hewgill Feb 14 '12 at 06:17
2

the answer I am getting is 7910956276398901000

You don't say what the expected answer is, but assuming it is something similar to what you are getting the problem is that JavaScript represents numbers using IEEE-754 double-precision (64 bit) format. As I understand it this gives you 53 bits precision, or fifteen to sixteen decimal digits. The number you are getting, 7910956276398901000, has more digits than JavaScript can cope with, so you end up with an approximation of the "real" answer.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
1

You could do it like this:

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>");
}

with the help of http://jsfromhell.com/classes/bignumber

The output is:

3
20
165
1814
25215
422800
8284753
185549202
4672333603
130609758204
4012046505613
134303337007166
4865394495960599
189626416079163448
7910956276398901049
Cheery
  • 16,063
  • 42
  • 57