UNPKG

906 BJavaScriptView Raw
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
8export default function() {
9 return new Adder;
10}
11
12function Adder() {
13 this.reset();
14}
15
16Adder.prototype = {
17 constructor: Adder,
18 reset: function() {
19 this.s = // rounded value
20 this.t = 0; // exact error
21 },
22 add: function(y) {
23 add(temp, y, this.t);
24 add(this, temp.s, this.s);
25 if (this.s) this.t += temp.t;
26 else this.s = temp.t;
27 },
28 valueOf: function() {
29 return this.s;
30 }
31};
32
33var temp = new Adder;
34
35function add(adder, a, b) {
36 var x = adder.s = a + b,
37 bv = x - a,
38 av = x - bv;
39 adder.t = (a - av) + (b - bv);
40}