Reputation: 882
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.
Upvotes: 3
Views: 1175
Reputation: 16214
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
Upvotes: 1
Reputation: 150080
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.
Upvotes: 2
Reputation: 993921
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.
Upvotes: 2