adder.js 906 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Adds floating point numbers with twice the normal precision.
  2. // Reference: J. R. Shewchuk, Adaptive Precision Floating-Point Arithmetic and
  3. // Fast Robust Geometric Predicates, Discrete & Computational Geometry 18(3)
  4. // 305–363 (1997).
  5. // Code adapted from GeographicLib by Charles F. F. Karney,
  6. // http://geographiclib.sourceforge.net/
  7. export default function() {
  8. return new Adder;
  9. }
  10. function Adder() {
  11. this.reset();
  12. }
  13. Adder.prototype = {
  14. constructor: Adder,
  15. reset: function() {
  16. this.s = // rounded value
  17. this.t = 0; // exact error
  18. },
  19. add: function(y) {
  20. add(temp, y, this.t);
  21. add(this, temp.s, this.s);
  22. if (this.s) this.t += temp.t;
  23. else this.s = temp.t;
  24. },
  25. valueOf: function() {
  26. return this.s;
  27. }
  28. };
  29. var temp = new Adder;
  30. function add(adder, a, b) {
  31. var x = adder.s = a + b,
  32. bv = x - a,
  33. av = x - bv;
  34. adder.t = (a - av) + (b - bv);
  35. }