0
# Epsilon-Based Equality
1
2
Floating-point equality comparison functions using epsilon tolerance to handle precision issues in numeric computations.
3
4
## Capabilities
5
6
### Fixed Epsilon Comparison
7
8
Basic epsilon-based equality checking with a fixed tolerance value.
9
10
```typescript { .api }
11
/**
12
* Checks if two numbers are equal within a fixed epsilon tolerance
13
* Returns true if |a - b| <= eps
14
* @param a - First value to compare
15
* @param b - Second value to compare
16
* @param eps - Epsilon tolerance (default: 1e-6)
17
* @returns True if values are equal within tolerance
18
*/
19
function eqDelta(a: number, b: number, eps?: number): boolean;
20
```
21
22
### Scaled Epsilon Comparison
23
24
Adaptive epsilon-based equality that scales tolerance based on the magnitude of input values.
25
26
```typescript { .api }
27
/**
28
* Checks if two numbers are equal using scaled epsilon tolerance
29
* Epsilon is factored with the largest absolute value: ε = ε * max(1, |a|, |b|)
30
* More appropriate for comparing larger numbers where absolute differences may be larger
31
* @param a - First value to compare
32
* @param b - Second value to compare
33
* @param eps - Base epsilon tolerance (default: 1e-6)
34
* @returns True if values are equal within scaled tolerance
35
*/
36
function eqDeltaScaled(a: number, b: number, eps?: number): boolean;
37
```
38
39
## Usage Examples
40
41
```typescript
42
import { eqDelta, eqDeltaScaled } from "@thi.ng/math/eqdelta";
43
44
// Fixed epsilon comparison
45
eqDelta(0.1 + 0.2, 0.3); // true (handles floating-point precision)
46
eqDelta(1.000001, 1.0); // false (difference exceeds default epsilon)
47
eqDelta(1.000001, 1.0, 1e-5); // true (with larger epsilon)
48
49
// Scaled epsilon comparison
50
eqDeltaScaled(1000.1, 1000.0); // true (scaled epsilon allows larger absolute difference)
51
eqDeltaScaled(0.1, 0.0); // false (scaled epsilon doesn't help with small numbers)
52
53
// Practical applications
54
const isNearZero = (x: number, eps = 1e-10) => eqDelta(x, 0, eps);
55
const isNearOne = (x: number, eps = 1e-10) => eqDelta(x, 1, eps);
56
57
// For large numbers, scaled comparison is better
58
const largeA = 1e10 + 1;
59
const largeB = 1e10;
60
eqDelta(largeA, largeB); // false (absolute difference is 1)
61
eqDeltaScaled(largeA, largeB); // true (relative difference is tiny)
62
63
// Comparing computation results
64
const computed = Math.sqrt(2) * Math.sqrt(2);
65
const expected = 2;
66
eqDelta(computed, expected); // true (handles computation precision errors)
67
68
// Array comparison with epsilon
69
const arraysEqual = (a: number[], b: number[], eps?: number) =>
70
a.length === b.length && a.every((val, i) => eqDelta(val, b[i], eps));
71
72
arraysEqual([0.1 + 0.2, 0.4 + 0.5], [0.3, 0.9]); // true
73
```