2

Out of curiosity, i'm coding a small JavaScript program to estimate the value of the number e, given by the series 1/n! from zero to infinity. The problem is that because of the IEEE 754 standard, my answer is rounded to 16 decimals, no matter how many terms I evaluate.

Is there a way to store the first 16 decimals in a string once the value reaches a point where new decimals aren't taken into account, then calculate the next 16 (and so on and so forth) and then add the strings together to get say 32,64 or 128 decimals?

What I have so far;

var e = 1;
var f = 1;

for (var n = 1; n < 1000; n++) {
  f *= n; //factorial
  e += (1 / f);
}

console.log(e);

This question does not pertain to rounding issues (as flagged).

Dat8StringGuy
  • 301
  • 1
  • 2
  • 10
  • 2
    as [this answer points out](http://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) the best route might be to use a library for this type of precision. [This is one the files mentioned in the post that may help](http://jsfromhell.com/classes/bignumber) – httpNick Oct 12 '16 at 21:16
  • What you could do is just store the value in a string and always perform all mathematical operations there. It's not pretty, but it's doable, I wouldn't call it hard, either, but it's definitely annoying as you basically have to re-invent maths in JS, only with strings. You could also split the number into several to accommodate the precision. If you need to "carry over" any digits that "overflow" your current number, you add them to the next one. Essentially, you'd have a list of numbers and concat them together for the total. You can also use a library that does that, e.g., bignumber.js – VLAZ Oct 12 '16 at 21:16
  • @vlaz You wouldn't use strings, you'd use a `Uint32Array` which is much more efficient, contains numbers by default, and is easily modifyable. – Bergi Oct 12 '16 at 21:38
  • @Bergi or that. Keep forgetting it exists. – VLAZ Oct 12 '16 at 21:40

0 Answers0