Reputation: 262
Im trying to get the euler number, with Javascript.
Here my code, that return infinity:
function euler_number() {
for(var j = 0, e = 0; j < 10; j++) {
e += 1/(factorial(j));
}
return e;
}
function factorial(n) {
if(n <= 1) return n;
return factorial(n - 1) * n;
}
var r = euler_number();
console.log(r);
so, i cant understand why it return infinity.
Upvotes: 0
Views: 169
Reputation: 211
This code returns infinity because the initial value of j
is 0
. In particular, you're adding 1/factorial(0)
to e
. What does factorial(0)
return? JavaScript evaluates 1/0
as Infinity
, so after the first iteration, e
is already Infinity
, and any subsequent iterations add more to it.
To fix this, just start j
at 1. That should do the trick!
Edit: Vasan had a great point, which is that 0! (0 factorial) actually evaluates to 1. For a better fix, you should reevaluate your factorial
function.
Upvotes: 2
Reputation: 1
Because your first value of j is 0. You divide that by zero and get infinity in JS. Whatever you add to it is still infinity
The following is your value of j in each of the 10 iteration
Infinity, 1, 0.5, 0.3333333333333333, 0.25, 0.2, 0.16666666666666666, 0.14285714285714285, 0.125, 0.1111111111111111,
Upvotes: 0