@numio/bigmath 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,55 +1,45 @@
1
- # @numio/bigmath
2
-
3
- @numio/bigmath is an arbitrary-precision arithmetic library. This library
4
- provides functions for performing arithmetic operations (addition, subtraction,
5
- multiplication, and division) on numbers of arbitrary length. It addresses the
6
- limitations of JavaScript's built-in number type, which suffers from precision
7
- loss when dealing with very large or very small numbers, or numbers with more
8
- than 15 significant digits.
9
-
10
- ## Key Features and Benefits
11
-
12
- - **Arbitrary Precision:** Handles numbers of any length, avoiding the
13
- limitations of JavaScript's `Number` type. This allows for calculations with
14
- extremely large or small numbers without loss of precision.
15
- - **No Precision Loss:** Eliminates precision errors that occur when using
16
- numeric literals with more than 15 significant digits. The library ensures
17
- accurate calculations even with very long numbers.
18
- - **Four Basic Operations:** Provides functions for addition (`add`),
19
- subtraction (`sub`), multiplication (`mul`), and division (`div`).
20
- - **Decimal Handling:** Correctly handles decimal numbers and performs
21
- calculations accurately, including scenarios involving negative numbers.
22
- - **Division Precision Control:** The `div` function allows you to specify the
23
- number of digits after the decimal point for the result. The default precision
24
- is 20 digits.
25
- - **Easy to Use:** The library provides simple and intuitive functions for
26
- performing arithmetic operations.
27
-
28
- ## How it Solves the Problem
29
-
30
- JavaScript's `Number` type uses a 64-bit floating-point representation (IEEE
31
- 754), which can lead to precision issues when dealing with numbers that exceed
32
- its representable range or require more than 15 significant digits. This library
33
- likely uses a different representation internally (e.g., strings or arrays of
34
- digits) to store and manipulate numbers, effectively bypassing the limitations
35
- of the built-in `Number` type. This allows it to perform calculations on numbers
36
- of virtually unlimited size and maintain accuracy.
37
-
38
- ## Use Cases
39
-
40
- This library is particularly useful in scenarios where precise calculations with
41
- large numbers are essential, such as:
42
-
43
- - **Financial applications:** Dealing with large sums of money or precise
44
- interest calculations.
45
- - **Scientific computing:** Working with very large or small numbers in
46
- scientific simulations.
47
- - **Cryptography:** Implementing cryptographic algorithms that require high
48
- precision.
49
- - **Any application** where exceeding JavaScript's number limits is a concern.
1
+ # @numio/bigmath: Precise Arithmetic Beyond JavaScript's Limits
2
+
3
+ **Do you struggle with inaccurate calculations involving very large or very small numbers, or decimal numbers with high precision in JavaScript?**
4
+
5
+ `@numio/bigmath` is your solution! This library provides a robust set of functions for performing **arbitrary-precision arithmetic**, effectively overcoming the limitations of JavaScript's built-in `Number` type. Say goodbye to unexpected rounding errors and precision loss when dealing with numbers that exceed 15 significant digits or involve complex decimal operations.
6
+
7
+ ## Why Choose @numio/bigmath?
8
+
9
+ **Solve Precision Problems:**
10
+
11
+ * **Handle Numbers of Any Size:** Perform calculations on integers and decimals of virtually unlimited length, without the risk of JavaScript's `Number` limitations.
12
+ * **Eliminate Precision Loss:** Achieve accurate results even with numeric literals exceeding 15 significant digits, ensuring the integrity of your calculations.
13
+ * **Precise Decimal Operations:** Execute addition, subtraction, multiplication, and division on decimal numbers with guaranteed accuracy, including scenarios with negative values.
14
+
15
+ **Unlock Advanced Numerical Operations:**
16
+
17
+ * **Control Division Precision:** Specify the exact number of digits after the decimal point for division results, with a default precision of 20 digits for high accuracy.
18
+ * **Flexible Rounding:** Round numbers to the nearest integer or a specific number of decimal places with various rounding modes (up, down, half-up, half-down, half-even, half-odd) to meet your exact requirements.
19
+ * **Round Based on Significant Figures:** Control rounding based on the number of significant figures, crucial for scientific and engineering applications.
20
+ * **Chain Operations with Pipe:** Simplify complex calculations by chaining arithmetic operations in a readable and intuitive manner.
21
+ * **Analyze Data Distribution:** Calculate quartiles (Q1, Q2, Q3) to understand the spread and central tendency of your numerical data, helping identify outliers and the shape of the distribution.
22
+ * **Sort Numbers Accurately:** Sort arrays of numbers, including negative and decimal values, in ascending or descending order, correctly handling string representations of numbers that JavaScript's native sort might misinterpret.
23
+ * **Calculate Central Tendency:** Easily compute the mean (average) of a set of numbers.
24
+ * **Identify Extremes:** Find the maximum and minimum values within an array of numbers.
25
+
26
+ ## When is @numio/bigmath essential?
27
+
28
+ This library is particularly invaluable in applications where numerical accuracy and the ability to handle large numbers are paramount:
29
+
30
+ * **Financial Applications:** Accurate calculations for large sums of money, precise interest rates, and complex financial modeling.
31
+ * **Scientific Computing:** Working with extremely large or small numbers in simulations, data analysis, and research.
32
+ * **Cryptography:** Implementing cryptographic algorithms that rely on high-precision arithmetic.
33
+ * **E-commerce and Payments:** Handling precise amounts and avoiding rounding errors in transactions.
34
+ * **Data Analysis and Statistics:** Performing accurate statistical calculations on datasets with varying scales.
35
+ * **Any Scenario Exceeding JavaScript's Number Limits:** Ensuring the reliability of your calculations when dealing with numbers beyond the safe integer limit or requiring more than 15 significant digits.
36
+
37
+ With `@numio/bigmath`, you can confidently perform complex arithmetic operations with the assurance of accuracy, regardless of the size or precision of the numbers involved.
50
38
 
51
39
  ### Latest update
52
40
 
41
+ Added sorting, min/max, mean.
42
+
53
43
  Added quartile functionality. When you might need it?
54
44
  Understanding Distribution. Quartiles (Q1, Q2, and Q3) split a dataset into four groups, each representing 25% of the data.
55
45
  Identifying Outliers. They help visualize the shape and spread of the data, revealing whether it's skewed or symmetrical.
@@ -123,12 +113,12 @@ const negative = mul(["-2", "3"]); // -6
123
113
  ```javascript
124
114
  import { div } from "@numio/bigmath";
125
115
 
126
- const int = div(["9999", "33"]); //
116
+ const int = div(["9999", "33"]); // 303
127
117
  const float = div(["0.06", "0.2"]); // 0.3
128
- const negative = div(["-2", "-3", "2"]); // 3
118
+ const negative = div(["-2", "-3", "2"]); //0.33333333333333333333
129
119
 
130
120
  // set number of digit after the decimal. By default it's 20
131
- div("10", "3"); // 3.33333
121
+ div(["10", "3"], 4); // 3.3333
132
122
  ```
133
123
 
134
124
  ### Round
@@ -210,7 +200,7 @@ pipe.add(addNums) // 6
210
200
  .div(divNums) // 6 / 4 = 1.5
211
201
  .sub(subNums) // 1.5 - 0.2 - 0.3 = 1
212
202
  .mul(mulNums) // 1 * 2 * 5 * 0.2 = 2
213
- .calc()
203
+ .calc() // convert end result to readable string
214
204
  ```
215
205
 
216
206
  ### Quartile
@@ -222,6 +212,45 @@ quartile(["0.001", "0.3", "0.4", "1"]) // { Q1: "0.1505", Q2: "0.35", Q3: "0.7"
222
212
 
223
213
  ```
224
214
 
215
+ ### Sort
216
+ ```javascript
217
+ import { sort } from "@numio/bigmath";
218
+
219
+ // native js sort for strings
220
+ ["1", "10", "11", "101", "11", "10", "1"].sort() // ["1", "1", "10", "10", "101", "11", "11"]
221
+
222
+ // sort from "@numio/bigmath"
223
+ sort(["1", "10", "11", "101", "11", "10", "1"]) // ["1", "1", "10", "10", "11", "11", "101"]
224
+
225
+ // ASC sorting
226
+ sort(["-0.1", "0.1", "-1"], "asc") // ["-1", "-0.1", "0.1"]
227
+
228
+ // DESC sorting
229
+ sort(["-0.1", "0.1", "-1"], "desc") // ["0.1", "-0.1", "1"]
230
+
231
+ ```
232
+
233
+ ### Mean
234
+ ```javascript
235
+ import { mean } from "@numio/bigmath";
236
+
237
+ mean(["5", "4", "3", "2", "1", "0"]) // "2.5"
238
+ mean(["0.5", "0.4", "0.3", "0.2", "0.1", "0"]) // "0.25"
239
+ ```
240
+
241
+ ### Max
242
+ ```javascript
243
+ import { max } from "@numio/bigmath";
244
+
245
+ max(["2", "-1", "0.1"]) // 2;
246
+ ```
247
+
248
+ ### Min
249
+ ```javascript
250
+ import { min } from "@numio/bigmath";
251
+
252
+ min(["2", "-1", "0.1"]) // -1;
253
+ ```
225
254
 
226
255
  Does not have a limitation on the number of digits. You can use any length you'd
227
256
  like
@@ -239,7 +268,10 @@ const float = mul(
239
268
  ); // 0.00000000000000000000000000000000000000000000000000000000000000000000000000018
240
269
  ```
241
270
 
242
- Download from NPM - https://www.npmjs.com/package/@numio/bigmath\
243
- Download from JSR - https://jsr.io/@numio/bigmath\
244
- Home page - https://github.com/shpunter/numio-bigmath/blob/main/README.md\
271
+ Download from NPM - https://www.npmjs.com/package/@numio/bigmath
272
+
273
+ Download from JSR - https://jsr.io/@numio/bigmath
274
+
275
+ Home page - https://github.com/shpunter/numio-bigmath/blob/main/README.md
276
+
245
277
  License - https://github.com/shpunter/numio-bigmath/blob/main/LICENSE
package/index.d.ts CHANGED
@@ -5,4 +5,7 @@ import { div } from "./src/mathOperations/div/index.d.ts";
5
5
  import { round } from "./src/round/index.d.ts";
6
6
  import { pipe } from "./src/pipe/main.d.ts";
7
7
  import { quartile } from "./src/quartile/main.d.ts";
8
- export { add, div, mul, pipe, quartile, round, sub };
8
+ import { sort } from "./src/sort/main.d.ts";
9
+ import { mean } from "./src/mean/main.d.ts";
10
+ import { min, max } from "./src/compare/main.d.ts";
11
+ export { add, div, max, mean, min, mul, pipe, quartile, round, sort, sub };
package/index.js CHANGED
@@ -5,4 +5,7 @@ import { div } from "./src/mathOperations/div/index.js";
5
5
  import { round } from "./src/round/index.js";
6
6
  import { pipe } from "./src/pipe/main.js";
7
7
  import { quartile } from "./src/quartile/main.js";
8
- export { add, div, mul, pipe, quartile, round, sub };
8
+ import { sort } from "./src/sort/main.js";
9
+ import { mean } from "./src/mean/main.js";
10
+ import { min, max } from "./src/compare/main.js";
11
+ export { add, div, max, mean, min, mul, pipe, quartile, round, sort, sub };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@numio/bigmath",
3
3
  "description": "@numio/bigmath is an arbitrary-precision arithmetic library. It can be used for basic operations with decimal numbers (integers and float)",
4
- "version": "1.0.5",
4
+ "version": "1.0.7",
5
5
  "keywords": [
6
6
  "precision",
7
7
  "arithmetic",
@@ -33,7 +33,12 @@
33
33
  "Q1",
34
34
  "Q2",
35
35
  "Q3",
36
- "round"
36
+ "round",
37
+ "min",
38
+ "max",
39
+ "sort",
40
+ "mean",
41
+ "significant figures"
37
42
  ],
38
43
  "repository": {
39
44
  "type": "git",
@@ -0,0 +1,9 @@
1
+ import type { CompareRawFn, Max, MaxRawFn, Min, MinRawFn } from "./types.d.ts";
2
+ export declare const compareRawFn: CompareRawFn;
3
+ export declare const maxRawFn: MaxRawFn;
4
+ export declare const minRawFn: MinRawFn;
5
+ /** This function returns max number. */
6
+ export declare const max: Max;
7
+ /** This function returns min number. */
8
+ export declare const min: Min;
9
+ export declare const isGreater: (l: string, r: string) => boolean;
@@ -0,0 +1,80 @@
1
+ import { a2s, s2a } from "../shared/utils.js";
2
+ export var compareRawFn = function (l, r) {
3
+ var _a;
4
+ var idx = 0;
5
+ var _b = [l, r], left = _b[0], right = _b[1];
6
+ var lIsNeg = l.isNegative, lIntLen = l.intLength;
7
+ var rIsNeg = r.isNegative, rIntLen = r.intLength;
8
+ var lenL = l.array.length;
9
+ var lenR = r.array.length;
10
+ var bothNeg = lIsNeg && rIsNeg;
11
+ var bothPos = !lIsNeg && !rIsNeg;
12
+ var bothIntPos = lIntLen > 0 && rIntLen > 0;
13
+ var bothIntNeg = lIntLen <= 0 && rIntLen <= 0;
14
+ if (lIsNeg && !rIsNeg)
15
+ return [r, false];
16
+ if (!lIsNeg && rIsNeg)
17
+ return [l, true];
18
+ if (bothPos && bothIntPos && lIntLen < rIntLen)
19
+ return [r, false];
20
+ if (bothPos && bothIntNeg && lIntLen < rIntLen)
21
+ return [r, false];
22
+ if (bothNeg && bothIntPos && lIntLen < rIntLen)
23
+ return [l, true];
24
+ if (bothNeg && bothIntNeg && lIntLen < rIntLen)
25
+ return [l, true];
26
+ if (bothNeg && bothIntNeg && lIntLen > rIntLen)
27
+ return [r, false];
28
+ if (bothNeg && bothIntPos && lIntLen > rIntLen)
29
+ return [r, false];
30
+ if (bothPos && bothIntPos && lIntLen > rIntLen)
31
+ return [l, true];
32
+ if (bothPos && bothIntNeg && lIntLen > rIntLen)
33
+ return [l, true];
34
+ if (bothNeg)
35
+ _a = [r, l], left = _a[0], right = _a[1];
36
+ while (idx < (lenL > lenR ? lenL : lenR)) {
37
+ var numL = left.array[idx];
38
+ var numR = right.array[idx];
39
+ if (!numL && bothPos)
40
+ return [r, false];
41
+ if (!numR && bothPos)
42
+ return [l, true];
43
+ if (!numL && bothNeg)
44
+ return [l, true];
45
+ if (!numR && bothNeg)
46
+ return [r, false];
47
+ if (numL !== numR) {
48
+ return numL > numR ? [l, true] : [r, false];
49
+ }
50
+ idx += 1;
51
+ }
52
+ return [l, true];
53
+ };
54
+ export var maxRawFn = function (array) {
55
+ var max = array[0];
56
+ for (var i = 1; i < array.length; i++) {
57
+ compareRawFn(max, array[i])[1] || (max = array[i]);
58
+ }
59
+ return max;
60
+ };
61
+ export var minRawFn = function (array) {
62
+ var min = array[0];
63
+ for (var i = 1; i < array.length; i++) {
64
+ compareRawFn(min, array[i])[1] && (min = array[i]);
65
+ }
66
+ return min;
67
+ };
68
+ /** This function returns max number. */
69
+ export var max = function (strs) {
70
+ var array = strs.map(function (str) { return s2a(str); });
71
+ return a2s(maxRawFn(array));
72
+ };
73
+ /** This function returns min number. */
74
+ export var min = function (strs) {
75
+ var array = strs.map(function (str) { return s2a(str); });
76
+ return a2s(minRawFn(array));
77
+ };
78
+ export var isGreater = function (l, r) {
79
+ return compareRawFn(s2a(l), s2a(r))[1];
80
+ };
@@ -0,0 +1,6 @@
1
+ import type { InputData } from "../types.d.ts";
2
+ export type CompareRawFn = (left: InputData, right: InputData) => [InputData, boolean];
3
+ export type Min = (strs: string[]) => string;
4
+ export type Max = (strs: string[]) => string;
5
+ export type MinRawFn = (array: InputData[]) => InputData;
6
+ export type MaxRawFn = (array: InputData[]) => InputData;
@@ -0,0 +1,3 @@
1
+ import type { Mean } from "./types.d.ts";
2
+ /** This function returns mean of an array. */
3
+ export declare const mean: Mean;
@@ -0,0 +1,5 @@
1
+ import { pipe } from "../pipe/main.js";
2
+ /** This function returns mean of an array. */
3
+ export var mean = function (array) {
4
+ return pipe.add(array).div([array.length.toString()]).calc();
5
+ };
@@ -0,0 +1 @@
1
+ export type Mean = (array: string[]) => string;
@@ -9,5 +9,6 @@ declare class Pipe {
9
9
  mul(strs: string[]): Pipe;
10
10
  calc(): ReturnType<A2S>;
11
11
  }
12
+ /** Using this function you can chain operations (add, sub, div, mul). */
12
13
  export declare const pipe: Pipe;
13
14
  export {};
package/src/pipe/main.js CHANGED
@@ -32,4 +32,5 @@ var Pipe = /** @class */ (function () {
32
32
  };
33
33
  return Pipe;
34
34
  }());
35
+ /** Using this function you can chain operations (add, sub, div, mul). */
35
36
  export var pipe = new Pipe();
@@ -1,2 +1,3 @@
1
1
  import type { Quartile } from "./types.d.ts";
2
+ /** This function returns Q1, Q2, Q3 (quartile). */
2
3
  export declare const quartile: Quartile;
@@ -2,6 +2,7 @@ import { pipe } from "../pipe/main.js";
2
2
  var mean = function (idx, array) {
3
3
  return pipe.add([array[idx], array[idx - 1]]).div(["2"]).calc();
4
4
  };
5
+ /** This function returns Q1, Q2, Q3 (quartile). */
5
6
  export var quartile = function (array) {
6
7
  if (array.length < 3) {
7
8
  throw Error("To calculate quartile you need at least 3 elements");
@@ -9,13 +9,13 @@ export var round = function (value, options) {
9
9
  var sigFig = (_c = options === null || options === void 0 ? void 0 : options.sigFig) !== null && _c !== void 0 ? _c : false;
10
10
  var decimals = (_d = options === null || options === void 0 ? void 0 : options.decimals) !== null && _d !== void 0 ? _d : 0;
11
11
  var isFloat = false;
12
- var isNill = true;
12
+ var isNil = true;
13
13
  for (var i = 0; i < value.length; i++) {
14
14
  var charCode = value.charCodeAt(i);
15
15
  if (sigFig && charCode > 48)
16
16
  sigFig = false;
17
- if (isNill && charCode > 48)
18
- isNill = false;
17
+ if (isNil && charCode > 48)
18
+ isNil = false;
19
19
  if (isFloat && !sigFig)
20
20
  decimals -= 1;
21
21
  if (charCode === 46)
@@ -39,7 +39,7 @@ export var round = function (value, options) {
39
39
  array.push(charCode);
40
40
  }
41
41
  handleTail(array, isFloat);
42
- return (isNill && array[array.length - 1] <= 48)
42
+ return (isNil && array[array.length - 1] <= 48)
43
43
  ? "0"
44
44
  : String.fromCharCode.apply(String, array);
45
45
  };
@@ -1,3 +1,6 @@
1
+ var convert = function (isNegative, array) {
2
+ return (isNegative ? "-" : "") + String.fromCharCode.apply(String, array);
3
+ };
1
4
  export var a2s = function (_a) {
2
5
  var array = _a.array, isFloat = _a.isFloat, isNegative = _a.isNegative, intLength = _a.intLength;
3
6
  var result = [];
@@ -21,23 +24,23 @@ export var a2s = function (_a) {
21
24
  }
22
25
  else {
23
26
  for (var i = 0; i < lastValuableIdx; i++) {
24
- if (i === intLength)
25
- result.push(46);
27
+ i === intLength && result.push(46);
26
28
  result.push(array[i]);
27
29
  }
28
30
  }
29
- return (isNegative ? "-" : "") + String.fromCharCode.apply(String, result);
31
+ return result.at(-1) === 46 ? "0" : convert(isNegative, result);
30
32
  }
31
- return (isNegative ? "-" : "") + String.fromCharCode.apply(String, array).trim();
33
+ return convert(isNegative, array);
32
34
  };
33
35
  export var s2a = function (string) {
34
36
  var array = Array(0);
35
37
  var isNegative = string.charCodeAt(0) === 45;
36
38
  var shift = isNegative ? 1 : 0;
37
39
  var dec = 0;
38
- if ((string.length === 1 && string.charCodeAt(0) === 48) ||
39
- string.length === 2 && string.charCodeAt(0) === 45 &&
40
- string.charCodeAt(1) === 48) {
40
+ var isNil = string.length === 1 && string.charCodeAt(0) === 48;
41
+ var isNegNil = string.length === 2 && string.charCodeAt(0) === 45 &&
42
+ string.charCodeAt(1) === 48;
43
+ if (isNil || isNegNil) {
41
44
  return {
42
45
  array: [48],
43
46
  intLength: 1,
@@ -0,0 +1,3 @@
1
+ export declare const ASC: "asc";
2
+ export declare const DESC: "desc";
3
+ export declare const sortingArray: ("asc" | "desc")[];
@@ -0,0 +1,3 @@
1
+ export var ASC = "asc";
2
+ export var DESC = "desc";
3
+ export var sortingArray = [ASC, DESC];
@@ -0,0 +1,3 @@
1
+ import type { Sort } from "./types.d.ts";
2
+ /** Using this function sort an array. */
3
+ export declare const sort: Sort;
@@ -0,0 +1,44 @@
1
+ import { compareRawFn } from "../compare/main.js";
2
+ import { a2s, s2a } from "../shared/utils.js";
3
+ import { ASC } from "./constants.js";
4
+ var heapify = function (array, len, i, sorting) {
5
+ var _a;
6
+ var idxL = 2 * i + 1;
7
+ var idxR = idxL + 1;
8
+ var idx = i;
9
+ if (sorting === ASC) {
10
+ if (idxL < len && compareRawFn(array[idxL], array[idx])[1])
11
+ idx = idxL;
12
+ if (idxR < len && compareRawFn(array[idxR], array[idx])[1])
13
+ idx = idxR;
14
+ }
15
+ else {
16
+ if (idxL < len && compareRawFn(array[idx], array[idxL])[1])
17
+ idx = idxL;
18
+ if (idxR < len && compareRawFn(array[idx], array[idxR])[1])
19
+ idx = idxR;
20
+ }
21
+ if (idx !== i) {
22
+ _a = [array[idx], array[i]], array[i] = _a[0], array[idx] = _a[1];
23
+ heapify(array, len, idx, sorting);
24
+ }
25
+ };
26
+ var sortRawFn = function (array, sorting) {
27
+ var _a;
28
+ var len = array.length;
29
+ for (var i = (len >> 1) - 1; i >= 0; i--) {
30
+ heapify(array, len, i, sorting);
31
+ }
32
+ for (var i = len - 1; i >= 0; i--) {
33
+ _a = [array[i], array[0]], array[0] = _a[0], array[i] = _a[1];
34
+ heapify(array, i, 0, sorting);
35
+ }
36
+ return array;
37
+ };
38
+ /** Using this function sort an array. */
39
+ export var sort = function (array, sorting) {
40
+ if (sorting === void 0) { sorting = ASC; }
41
+ var inputDataArray = array.map(function (str) { return s2a(str); });
42
+ sortRawFn(inputDataArray, sorting);
43
+ return inputDataArray.map(function (input) { return a2s(input); });
44
+ };
@@ -0,0 +1,6 @@
1
+ import type { InputData } from "../types.d.ts";
2
+ import type { sortingArray } from "./constants.d.ts";
3
+ export type Sorting = typeof sortingArray[number];
4
+ export type Sort = (array: string[], sorting?: Sorting) => string[];
5
+ export type SortRawFn = (array: InputData[], sorting: Sorting) => InputData[];
6
+ export type Heapify = (array: InputData[], len: number, i: number, sorting: Sorting) => void;