0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
ESCM
  • 269
  • 2
  • 13
  • `(factorial(j)` when `j=0` is `0` and `1/0` ? what else do you expect ? – Muhammad Usman Apr 25 '18 at 21:38
  • 1
    To add to the other comment, you may want to change the return to 1, since `0! === 1`. eg `if (n <= 1) return 1` – CRice Apr 25 '18 at 21:40
  • Also it's unclear from the title if you're trying to generate the famous [Euler constant `e`](https://en.wikipedia.org/wiki/E_(mathematical_constant)), or if you're trying to generate one of the [Euler Numbers](https://en.wikipedia.org/wiki/Euler_number), although the code clearly indicates the former. – CRice Apr 25 '18 at 21:43

2 Answers2

2

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.

Alex
  • 211
  • 1
  • 5
  • 2
    _What does factorial(0) return?_ - that is the real problem, a faulty factorial implementation.. – Vasan Apr 25 '18 at 21:57
  • @Mattiu I've rolled back your edit, since it removed the problem that this answer addresses. – Barmar Apr 25 '18 at 22:36
0

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,

binoy
  • 1