0
# Utility Functions
1
2
Additional mathematical utilities including prime numbers, permutations, safe operations, and specialized calculations.
3
4
## Capabilities
5
6
### Prime Number Operations
7
8
Functions for working with prime numbers.
9
10
```typescript { .api }
11
/**
12
* Returns generator of all prime numbers ≤ given x using Sieve of Eratosthenes
13
* @param x - Upper limit for prime generation
14
* @returns Generator yielding prime numbers in ascending order
15
*/
16
function primesUntil(x: number): Generator<number>;
17
18
/**
19
* Returns largest prime number ≤ given x
20
* @param x - Upper limit for prime search
21
* @returns Largest prime ≤ x, or -1 if x < 1
22
*/
23
function nearestPrime(x: number): number;
24
```
25
26
**Usage Examples:**
27
28
```typescript
29
import { primesUntil, nearestPrime } from "@thi.ng/math/prime";
30
31
// Generate all primes up to 30
32
const primes = [...primesUntil(30)]; // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
33
34
// Find largest prime less than or equal to a number
35
const prime = nearestPrime(100); // 97
36
const noPrime = nearestPrime(1); // -1 (no primes ≤ 1)
37
38
// Use in algorithms requiring prime numbers
39
function generatePrimeTable(limit: number): number[] {
40
return [...primesUntil(limit)];
41
}
42
```
43
44
### Permutations and Combinations
45
46
Functions for combinatorial mathematics.
47
48
```typescript { .api }
49
/**
50
* Computes factorial for n: n!
51
* @param n - Non-negative integer
52
* @returns n! (factorial of n)
53
* @throws Error if n < 0
54
*/
55
function factorial(n: number): number;
56
57
/**
58
* Computes n^k (permutations with repetition)
59
* @param n - Number of choices for each position
60
* @param k - Number of positions
61
* @returns Number of permutations with repetition
62
*/
63
function permutationsWithRep(n: number, k: number): number;
64
65
/**
66
* Computes n!/(n-k)! (permutations without repetition)
67
* @param n - Total number of items
68
* @param k - Number of items to choose
69
* @returns Number of permutations without repetition
70
*/
71
function permutationsWithoutRep(n: number, k: number): number;
72
73
/**
74
* Computes (n+k-1)!/(k!*(n-1)!) (combinations with repetition)
75
* @param n - Number of types of items
76
* @param k - Number of items to choose
77
* @returns Number of combinations with repetition
78
*/
79
function combinationsWithRep(n: number, k: number): number;
80
81
/**
82
* Computes n!/(k!*(n-k)!) (combinations without repetition)
83
* @param n - Total number of items
84
* @param k - Number of items to choose
85
* @returns Number of combinations without repetition (binomial coefficient)
86
*/
87
function combinationsWithoutRep(n: number, k: number): number;
88
```
89
90
**Usage Examples:**
91
92
```typescript
93
import {
94
factorial, permutationsWithRep, permutationsWithoutRep,
95
combinationsWithRep, combinationsWithoutRep
96
} from "@thi.ng/math/permutations";
97
98
// Basic factorial
99
const fact5 = factorial(5); // 120
100
101
// Password combinations: 4 digits, each 0-9
102
const passwords = permutationsWithRep(10, 4); // 10,000
103
104
// Arrange 5 people in 3 chairs (order matters)
105
const arrangements = permutationsWithoutRep(5, 3); // 60
106
107
// Choose 3 items from 4 types, repetition allowed
108
const withRep = combinationsWithRep(4, 3); // 20
109
110
// Choose 3 people from 5 (order doesn't matter)
111
const binomial = combinationsWithoutRep(5, 3); // 10 (C(5,3))
112
```
113
114
### Safe Operations
115
116
Functions that handle edge cases and provide safe alternatives to standard operations.
117
118
```typescript { .api }
119
/**
120
* Returns a divided by b, or zero if b = 0
121
* @param a - Dividend
122
* @param b - Divisor
123
* @returns a/b if b ≠ 0, otherwise 0
124
*/
125
function safeDiv(a: number, b: number): number;
126
```
127
128
**Usage Examples:**
129
130
```typescript
131
import { safeDiv } from "@thi.ng/math/safe-div";
132
133
// Safe division prevents NaN/Infinity results
134
const result1 = safeDiv(10, 2); // 5
135
const result2 = safeDiv(10, 0); // 0 (safe, not Infinity)
136
const result3 = safeDiv(0, 0); // 0 (safe, not NaN)
137
138
// Useful in algorithms where division by zero might occur
139
function average(values: number[]): number {
140
const sum = values.reduce((a, b) => a + b, 0);
141
return safeDiv(sum, values.length);
142
}
143
144
const avg1 = average([1, 2, 3, 4]); // 2.5
145
const avg2 = average([]); // 0 (safe handling of empty array)
146
```
147
148
### Absolute Value Operations
149
150
Functions for absolute value calculations and comparisons.
151
152
```typescript { .api }
153
/**
154
* Returns the absolute difference between a and b
155
* @param a - First value
156
* @param b - Second value
157
* @returns |a - b|
158
*/
159
function absDiff(a: number, b: number): number;
160
161
/**
162
* Similar to Math.sign(), but uses eps to determine the zero value
163
* @param x - Input value
164
* @param eps - Epsilon threshold for zero determination
165
* @returns -1, 0, or 1 based on sign of x
166
*/
167
function sign(x: number, eps?: number): number;
168
169
/**
170
* Raises x to k power and multiplies it with the sign of x
171
* @param x - Base value
172
* @param k - Exponent
173
* @param eps - Epsilon threshold for zero determination
174
* @returns sign(x) * |x|^k
175
*/
176
function signedPow(x: number, k: number, eps?: number): number;
177
```
178
179
**Usage Examples:**
180
181
```typescript
182
import { absDiff, sign, signedPow } from "@thi.ng/math/abs";
183
184
// Absolute difference
185
const diff = absDiff(-5, 3); // 8
186
const same = absDiff(7, 7); // 0
187
188
// Epsilon-aware sign function
189
const s1 = sign(0.0000001, 1e-6); // 1 (above epsilon)
190
const s2 = sign(0.0000001, 1e-5); // 0 (within epsilon of zero)
191
const s3 = sign(-2.5); // -1
192
193
// Signed power preserves sign
194
const sp1 = signedPow(-2, 3); // -8 (negative cube root of 8)
195
const sp2 = signedPow(3, 2); // 9 (positive)
196
const sp3 = signedPow(-4, 0.5); // -2 (negative square root)
197
```
198
199
### Ratio Operations
200
201
Functions for working with ratios and fractions.
202
203
```typescript { .api }
204
/**
205
* Simplifies a ratio by finding the GCD and reducing both terms
206
* @param num - Numerator
207
* @param denom - Denominator
208
* @returns Tuple [simplified_num, simplified_denom]
209
*/
210
function simplifyRatio(num: number, denom: number): [number, number];
211
```
212
213
**Usage Examples:**
214
215
```typescript
216
import { simplifyRatio } from "@thi.ng/math/ratio";
217
218
// Simplify fractions/ratios
219
const simple1 = simplifyRatio(8, 12); // [2, 3] (8/12 = 2/3)
220
const simple2 = simplifyRatio(15, 25); // [3, 5] (15/25 = 3/5)
221
const simple3 = simplifyRatio(7, 13); // [7, 13] (already simplified)
222
223
// Use in aspect ratio calculations
224
function simplifyAspectRatio(width: number, height: number): string {
225
const [w, h] = simplifyRatio(width, height);
226
return `${w}:${h}`;
227
}
228
229
const aspect1 = simplifyAspectRatio(1920, 1080); // "16:9"
230
const aspect2 = simplifyAspectRatio(1024, 768); // "4:3"
231
```
232
233
### Line Crossing Detection
234
235
Functions for detecting and classifying line crossings.
236
237
```typescript { .api }
238
/**
239
* Returns true if line A rises up over B
240
* @param a1 - Start point of line A
241
* @param a2 - End point of line A
242
* @param b1 - Start point of line B
243
* @param b2 - End point of line B
244
* @returns True if A crosses over B
245
*/
246
function isCrossOver(a1: number, a2: number, b1: number, b2: number): boolean;
247
248
/**
249
* Returns true if line A crosses under B
250
* @param a1 - Start point of line A
251
* @param a2 - End point of line A
252
* @param b1 - Start point of line B
253
* @param b2 - End point of line B
254
* @returns True if A crosses under B
255
*/
256
function isCrossUnder(a1: number, a2: number, b1: number, b2: number): boolean;
257
258
/**
259
* Returns Crossing classifier indicating the relationship of line A to line B
260
* @param a1 - Start point of line A
261
* @param a2 - End point of line A
262
* @param b1 - Start point of line B
263
* @param b2 - End point of line B
264
* @param eps - Epsilon for equality testing
265
* @returns Crossing classification
266
*/
267
function classifyCrossing(
268
a1: number, a2: number, b1: number, b2: number, eps?: number
269
): Crossing;
270
```
271
272
**Usage Examples:**
273
274
```typescript
275
import { isCrossOver, isCrossUnder, classifyCrossing } from "@thi.ng/math/crossing";
276
277
// Detect line crossings (useful for technical analysis, signal processing)
278
const crossOver = isCrossOver(1, 3, 2, 1); // true (A goes from below to above B)
279
const crossUnder = isCrossUnder(3, 1, 2, 4); // true (A goes from above to below B)
280
281
// Classify crossing type
282
const classification = classifyCrossing(1, 3, 2, 2); // "over" (A crosses over flat B)
283
const equalLines = classifyCrossing(1, 2, 1, 2); // "equal" (identical lines)
284
285
// Use in trading algorithms
286
function detectGoldenCross(shortMA: number[], longMA: number[]): boolean {
287
const lastShort = shortMA[shortMA.length - 1];
288
const prevShort = shortMA[shortMA.length - 2];
289
const lastLong = longMA[longMA.length - 1];
290
const prevLong = longMA[longMA.length - 2];
291
292
return isCrossOver(prevShort, lastShort, prevLong, lastLong);
293
}
294
```
295
296
### Specialized Minimization
297
298
Advanced minimization functions for optimization problems.
299
300
```typescript { .api }
301
/**
302
* Recursively finds the parameter value that minimizes error between function output and target value
303
* @param fn - Function to minimize error for
304
* @param error - Error calculation function
305
* @param q - Target value
306
* @param res - Resolution (optional)
307
* @param iter - Maximum iterations (optional)
308
* @param start - Search start value (optional)
309
* @param end - Search end value (optional)
310
* @param eps - Convergence epsilon (optional)
311
* @returns Parameter value that minimizes error
312
*/
313
function minError<T>(
314
fn: (x: number) => T,
315
error: (p: T, q: T) => number,
316
q: T,
317
res?: number,
318
iter?: number,
319
start?: number,
320
end?: number,
321
eps?: number
322
): number;
323
```
324
325
**Usage Examples:**
326
327
```typescript
328
import { minError } from "@thi.ng/math/min-error";
329
330
// Find parameter that makes function output closest to target
331
const fn = (x: number) => x * x; // f(x) = x²
332
const errorFn = (a: number, b: number) => Math.abs(a - b);
333
const target = 25; // Want f(x) = 25
334
335
const bestX = minError(fn, errorFn, target); // Should find x ≈ 5
336
337
// Complex optimization example
338
const complexFn = (t: number) => Math.sin(t) * Math.cos(t * 2);
339
const targetValue = 0.5;
340
const optimalT = minError(complexFn, errorFn, targetValue, 0.01, 100, 0, Math.PI);
341
```