javascriptalgorithm

Calculating Euler's Number to nth digit in javascript


How to calculate Euler's Number to nth digit in JavaScript?

e   =   1/0! + 1/1! + 1/2! + ...    
    =   2.7182818284590...to nth digit  (base 10)

Below code returns only number to 16 decimal point and accuracy is depend upon to the number of iterations/or number passed to function.

Code

function calcE(n) {
  let euler, itr;
  euler = 0
  itr = Number(n)
    for (var i = 0; i < itr+1; i++) {
      let fact = factorial(i)
      euler += 1/fact
    }
  return euler;
}

Demo: miniwebtool


Solution

  • Found a solution by using npm decimal.js package to handle big decimal.

    Euler

    function euler(n) {
      let zero = new Decimal(0);
      let one = new Decimal(1);
      let rval;
    
      for (let i = 0; i <= n; i++) {
        let fval = factorial(i);
        let invert = one.dividedBy(fval)
        zero = zero.plus(invert)
      }
      rval = zero.toFixed(Number(n))
      return rval;
    }
    
    function factorial(n) {
      var i = 2,
        r = new Decimal(1);
      for (; i <= n; r = r.times(i++));
      return r;
    }
    

    Still not able to compute very large values. An Suggestions?