source: node_modules/d3-array/src/fsum.js@ e4c61dd

Last change on this file since e4c61dd was e4c61dd, checked in by istevanoska <ilinastevanoska@…>, 6 months ago

Prototype 1.1

  • Property mode set to 100644
File size: 1.6 KB
Line 
1// https://github.com/python/cpython/blob/a74eea238f5baba15797e2e8b570d153bc8690a7/Modules/mathmodule.c#L1423
2export class Adder {
3 constructor() {
4 this._partials = new Float64Array(32);
5 this._n = 0;
6 }
7 add(x) {
8 const p = this._partials;
9 let i = 0;
10 for (let j = 0; j < this._n && j < 32; j++) {
11 const y = p[j],
12 hi = x + y,
13 lo = Math.abs(x) < Math.abs(y) ? x - (hi - y) : y - (hi - x);
14 if (lo) p[i++] = lo;
15 x = hi;
16 }
17 p[i] = x;
18 this._n = i + 1;
19 return this;
20 }
21 valueOf() {
22 const p = this._partials;
23 let n = this._n, x, y, lo, hi = 0;
24 if (n > 0) {
25 hi = p[--n];
26 while (n > 0) {
27 x = hi;
28 y = p[--n];
29 hi = x + y;
30 lo = y - (hi - x);
31 if (lo) break;
32 }
33 if (n > 0 && ((lo < 0 && p[n - 1] < 0) || (lo > 0 && p[n - 1] > 0))) {
34 y = lo * 2;
35 x = hi + y;
36 if (y == x - hi) hi = x;
37 }
38 }
39 return hi;
40 }
41}
42
43export function fsum(values, valueof) {
44 const adder = new Adder();
45 if (valueof === undefined) {
46 for (let value of values) {
47 if (value = +value) {
48 adder.add(value);
49 }
50 }
51 } else {
52 let index = -1;
53 for (let value of values) {
54 if (value = +valueof(value, ++index, values)) {
55 adder.add(value);
56 }
57 }
58 }
59 return +adder;
60}
61
62export function fcumsum(values, valueof) {
63 const adder = new Adder();
64 let index = -1;
65 return Float64Array.from(values, valueof === undefined
66 ? v => adder.add(+v || 0)
67 : v => adder.add(+valueof(v, ++index, values) || 0)
68 );
69}
Note: See TracBrowser for help on using the repository browser.