-
-
Notifications
You must be signed in to change notification settings - Fork 115
/
number.gr
755 lines (706 loc) 路 19.7 KB
/
number.gr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
/**
* Utilities for working with numbers.
*
* @example include "number"
*
* @since v0.4.0
*/
module Number
include "runtime/unsafe/wasmi32"
include "runtime/unsafe/wasmi64"
include "runtime/unsafe/wasmf32"
include "runtime/unsafe/wasmf64"
include "runtime/unsafe/memory"
include "runtime/dataStructures"
from DataStructures use { newFloat64, allocateString }
include "runtime/numbers"
from Numbers use {
coerceNumberToWasmF64,
reducedInteger,
isFloat,
isInteger,
isRational,
isBoxedNumber,
isNaN,
}
include "runtime/atoi/parse" as Atoi
include "runtime/atof/parse" as Atof
include "runtime/unsafe/tags"
include "runtime/exception"
from Atoi use { type ParseIntError }
provide { type ParseIntError }
/**
* Pi represented as a Number value.
*
* @since v0.5.2
*/
provide let pi = 3.141592653589793
/**
* Tau represented as a Number value.
*
* @since v0.5.2
*/
provide let tau = 6.283185307179586
/**
* Euler's number represented as a Number value.
*
* @since v0.5.2
*/
provide let e = 2.718281828459045
/**
* Computes the sum of its operands.
*
* @param num1: The first operand
* @param num2: The second operand
* @returns The sum of the two operands
*
* @since v0.6.0
* @history v0.4.0: Originally named `add`
*/
provide let (+) = (+)
/**
* Computes the difference of its operands.
*
* @param num1: The first operand
* @param num2: The second operand
* @returns The difference of the two operands
*
* @since v0.6.0
* @history v0.4.0: Originally named `sub`
*/
provide let (-) = (-)
/**
* Computes the product of its operands.
*
* @param num1: The first operand
* @param num2: The second operand
* @returns The product of the two operands
*
* @since v0.6.0
* @history v0.4.0: Originally named `mul`
*/
provide let (*) = (*)
/**
* Computes the quotient of its operands.
*
* @param num1: The dividend
* @param num2: The divisor
* @returns The quotient of the two operands
*
* @since v0.6.0
* @history v0.4.0: Originally named `div`
*/
provide let (/) = (/)
/**
* Computes the exponentiation of the given base and power.
*
* @param base: The base number
* @param power: The exponent number
* @returns The base raised to the given power
*
* @since v0.6.0
* @history v0.5.4: Originally named `pow`
*/
provide let (**) = (**)
/**
* Computes the exponentiation of Euler's number to the given power.
*
* @param power: The exponent number
* @returns The `Number.e` value raised to the given power
*
* @since v0.5.4
*/
provide let exp = power => {
if (power == 0) 1 else e ** power
}
/**
* Computes the square root of its operand.
*
* @param x: The number to square root
* @returns The square root of the operand
*
* @since v0.4.0
*/
@unsafe
provide let sqrt = (x: Number) => {
from WasmF64 use { (==) }
let xval = coerceNumberToWasmF64(x)
let x = WasmI32.fromGrain(x)
let sqrtd = WasmF64.sqrt(xval)
if (!isFloat(x) && sqrtd == WasmF64.trunc(sqrtd)) {
WasmI32.toGrain(reducedInteger(WasmI64.truncF64S(sqrtd))): Number
} else {
WasmI32.toGrain(newFloat64(sqrtd)): Number
}
}
/**
* Determine the positivity or negativity of a Number.
*
* @param x: The number to inspect
* @returns `-1` if the number is negative, `1` if positive, or `0` otherwise; signedness of `-0.0` is preserved
*
* @example Number.sign(-10000) == -1
* @example Number.sign(222222) == 1
* @example Number.sign(0) == 0
*/
provide let sign = x => {
match (x) {
x when x < 0 => -1,
x when x > 0 => 1,
_ => 0 * x,
}
}
/**
* Returns the smaller of its operands.
*
* @param x: The first operand
* @param y: The second operand
* @returns The smaller of the two operands
*
* @since v0.4.0
* @history v0.5.4: Handle NaN properly
*/
provide let min = (x: Number, y: Number) => if (compare(x, y) < 0) x else y
/**
* Returns the larger of its operands.
*
* @param x: The first operand
* @param y: The second operand
* @returns The larger of the two operands
*
* @since v0.4.0
* @history v0.5.4: Handle NaN properly
*/
provide let max = (x: Number, y: Number) => if (compare(x, y) > 0) x else y
/**
* Rounds its operand up to the next largest integer.
*
* @param x: The number to round
* @returns The next largest integer of the operand
*
* @since v0.4.0
* @history v0.5.4: Handle NaN and Infinity properly
*/
@unsafe
provide let ceil = (x: Number) => {
if (x != x) {
NaN
} else if (x == Infinity) {
Infinity
} else {
let xval = coerceNumberToWasmF64(x)
let ceiling = WasmI64.truncF64S(WasmF64.ceil(xval))
WasmI32.toGrain(reducedInteger(ceiling)): Number
}
}
/**
* Rounds its operand down to the largest integer less than the operand.
*
* @param x: The number to round
* @returns The previous integer of the operand
*
* @since v0.4.0
* @history v0.5.4: Handle NaN and Infinity properly
*/
@unsafe
provide let floor = (x: Number) => {
if (x != x) {
NaN
} else if (x == Infinity) {
Infinity
} else {
let xval = coerceNumberToWasmF64(x)
let floored = WasmI64.truncF64S(WasmF64.floor(xval))
WasmI32.toGrain(reducedInteger(floored)): Number
}
}
/**
* Returns the integer part of its operand, removing any fractional value.
*
* @param x: The number to truncate
* @returns The integer part of the operand
*
* @since v0.4.0
* @history v0.5.4: Handle NaN and Infinity properly
*/
@unsafe
provide let trunc = (x: Number) => {
if (x != x) {
NaN
} else if (x == Infinity) {
Infinity
} else {
let xval = coerceNumberToWasmF64(x)
let trunced = WasmI64.truncF64S(xval)
WasmI32.toGrain(reducedInteger(trunced)): Number
}
}
/**
* Returns its operand rounded to its nearest integer.
*
* @param x: The number to round
* @returns The nearest integer to the operand
*
* @since v0.4.0
* @history v0.5.4: Handle NaN and Infinity properly
*/
@unsafe
provide let round = (x: Number) => {
if (x != x) {
NaN
} else if (x == Infinity) {
Infinity
} else {
let xval = coerceNumberToWasmF64(x)
let rounded = WasmI64.truncF64S(WasmF64.nearest(xval))
WasmI32.toGrain(reducedInteger(rounded)): Number
}
}
/**
* Returns the absolute value of a number. That is, it returns `x` if `x` is positive or zero and the negation of `x` if `x` is negative.
*
* @param x: The operand
* @returns The absolute value of the operand
*
* @since v0.4.0
*/
provide let abs = (x: Number) => if (0 > x) x * -1 else x
/**
* Returns the negation of its operand.
*
* @param x: The number to negate
* @returns The negated operand
*
* @since v0.4.0
*/
provide let neg = (x: Number) => x * -1
/**
* Checks if a number is a floating point value.
*
* @param x: The number to check
* @returns `true` if the value is a floating point number or `false` otherwise
*
* @since v0.5.3
*/
@unsafe
provide let isFloat = (x: Number) => {
isFloat(WasmI32.fromGrain(x))
}
/**
* Checks if a number is an integer.
*
* @param x: The number to check
* @returns `true` if the value is an integer or `false` otherwise
*
* @since v0.5.3
*/
@unsafe
provide let isInteger = (x: Number) => {
isInteger(WasmI32.fromGrain(x))
}
/**
* Checks if a number is a non-integer rational value.
*
* @param x: The number to check
* @returns `true` if the value is a non-integer rational number or `false` otherwise
*
* @since v0.5.3
*/
@unsafe
provide let isRational = (x: Number) => {
isRational(WasmI32.fromGrain(x))
}
/**
* Checks if a number is finite.
* All values are finite exept for floating point NaN, infinity or negative infinity.
*
* @param x: The number to check
* @returns `true` if the value is finite or `false` otherwise
*
* @since v0.4.0
*/
@unsafe
provide let isFinite = (x: Number) => {
from WasmI32 use { (==) }
let asPtr = WasmI32.fromGrain(x)
if (isBoxedNumber(asPtr)) {
// Boxed numbers can have multiple subtypes, of which float32 and float64 can be infinite.
let tag = WasmI32.load(asPtr, 4n)
if (tag == Tags._GRAIN_FLOAT64_BOXED_NUM_TAG) {
from WasmF64 use { (-), (==) }
// uses the fact that all finite floats minus themselves are zero
// (NaN - NaN == NaN, inf - inf == NaN,
// -inf - -inf == NaN, inf - -inf == inf, -inf - inf == -inf)
let wf64 = WasmF64.load(asPtr, 8n)
wf64 - wf64 == 0.0W
} else {
// Neither rational numbers nor boxed integers can be infinite or NaN.
// Grain doesn't allow creating a rational with denominator of zero either.
true
}
} else {
// Simple numbers are integers and cannot be infinite.
true
}
}
/**
* Checks if a number is the float NaN value (Not A Number).
*
* @param x: The number to check
* @returns `true` if the value is NaN, otherwise `false`
*
* @since v0.4.0
*/
@unsafe
provide let isNaN = (x: Number) => {
let asPtr = WasmI32.fromGrain(x)
isNaN(asPtr)
}
/**
* Checks if a number is infinite, that is either of floating point positive or negative infinity.
* Note that this function is not the exact opposite of isFinite(Number) in that it doesn't return true for NaN.
*
* @param x: The number to check
* @returns `true` if the value is infinite or `false` otherwise
*
* @since v0.4.0
*/
@unsafe
provide let isInfinite = (x: Number) => {
from WasmI32 use { (==) }
// The following code is equivalent to (!isFinite(x) && !isNaN(x)),
// so see those functions to understand what's going on here.
let asPtr = WasmI32.fromGrain(x)
if (isBoxedNumber(asPtr)) {
let tag = WasmI32.load(asPtr, 4n)
if (tag == Tags._GRAIN_FLOAT64_BOXED_NUM_TAG) {
from WasmF64 use { (-), (==), (!=) }
let wf64 = WasmF64.load(asPtr, 8n)
wf64 - wf64 != 0.0W && wf64 == wf64
} else {
false
}
} else {
false
}
}
/**
* Parses a string representation of an integer into a `Number` using the
* specified radix (also known as a number system "base").
*
* If the string has a radix prefix (i.e. "0x"/"0X", "0o"/"0O", or "0b"/"0B"
* for radixes 16, 8, or 2 respectively), the supplied radix is ignored in
* favor of the prefix. Underscores that appear in the numeric portion of the
* input are ignored.
*
* @param string: The string to parse
* @param radix: The number system base to use when parsing the input string
* @returns `Ok(value)` containing the parsed number on a successful parse or `Err(msg)` containing an error message string otherwise
*
* @since v0.4.5
*/
provide let parseInt = Atoi.parseInt
/**
* Parses a string representation of a float into a `Number`. Underscores that appear
* in numeric portions of the input are ignored.
*
* @param string: The string to parse
* @returns `Ok(value)` containing the parsed number on a successful parse or `Err(msg)` containing an error message string otherwise
*
* @since v0.5.5
*/
provide let parseFloat = Atof.parseFloat
/**
* Parses a string representation of an integer, float, or rational into a `Number`.
* Underscores that appear in the numeric portion of the input are ignored.
*
* @param input: The string to parse
* @returns `Ok(value)` containing the parsed number on a successful parse or `Err(msg)` containing an error message string otherwise
*
* @since v0.5.5
*/
@unsafe
provide let parse = input => {
match (parseInt(input, 10)) {
Ok(number) => Ok(number),
Err(msg) =>
match (parseFloat(input)) {
Ok(number) => Ok(number),
Err(_) => {
// Split the input on a `/` and attempt to parse a rational
from WasmI32 use { (+), (-), ltU as (<), (==) }
// Search for `/`
let input = WasmI32.fromGrain(input)
let len = WasmI32.load(input, 4n)
let mut slashIdx = -1n
for (let mut i = 0n; i < len; i += 1n) {
if (WasmI32.load8U(input + i, 8n) == 0x2fn) {
slashIdx = i
break
}
}
if (slashIdx == -1n) {
Err(msg)
} else {
let numeratorLen = slashIdx
let denominatorLen = len - slashIdx - 1n
let numerator = allocateString(numeratorLen)
Memory.copy(numerator + 8n, input + 8n, numeratorLen)
let numerator = WasmI32.toGrain(numerator): String
let denominator = allocateString(denominatorLen)
Memory.copy(
denominator + 8n,
input + 8n + slashIdx + 1n,
denominatorLen
)
let denominator = WasmI32.toGrain(denominator): String
match ((parseInt(numerator, 10), parseInt(denominator, 10))) {
(Ok(numerator), Ok(denominator)) => Ok(numerator / denominator),
(Err(msg), _) | (_, Err(msg)) => Err(msg),
}
}
},
},
}
}
/**
* Computes how many times pi has to be subtracted to achieve the required bounds for sin.
*/
let reduceToPiBound = (radians: Number) => {
floor(radians / pi)
}
/**
* Computes the sine of a number using Chebyshev polynomials. Requires the input to be bounded to (-pi, pi). More information on the algorithm can be found here: http://mooooo.ooo/chebyshev-sine-approximation/.
*/
let chebyshevSine = (radians: Number) => {
let pi_minor = -0.00000008742278
let x2 = radians * radians
let p11 = 0.00000000013291342
let p9 = p11 * x2 + -0.000000023317787
let p7 = p9 * x2 + 0.0000025222919
let p5 = p7 * x2 + -0.00017350505
let p3 = p5 * x2 + 0.0066208798
let p1 = p3 * x2 + -0.10132118
(radians - pi - pi_minor) * (radians + pi + pi_minor) * p1 * radians
}
/**
* Computes the sine of a number (in radians) using Chebyshev polynomials.
*
* @param radians: The input in radians
* @returns The computed sine
*
* @since v0.5.2
* @history v0.5.4: Handle NaN and Infinity
*/
provide let sin = (radians: Number) => {
if (radians != radians || radians == Infinity) {
NaN
} else {
let quot = reduceToPiBound(radians)
let bounded = radians - pi * quot
if (quot % 2 == 0) {
chebyshevSine(bounded)
} else {
neg(chebyshevSine(bounded))
}
}
}
/**
* Computes the cosine of a number (in radians) using Chebyshev polynomials.
*
* @param radians: The input in radians
* @returns The computed cosine
*
* @since v0.5.2
* @history v0.5.4: Handle NaN and Infinity
*/
provide let cos = (radians: Number) => {
if (radians != radians || radians == Infinity) {
NaN
} else {
sin(pi / 2 + radians)
}
}
/**
* Computes the tangent of a number (in radians) using Chebyshev polynomials.
*
* @param radians: The input in radians
* @returns The computed tangent
*
* @since v0.5.4
*/
provide let tan = (radians: Number) => {
if (isNaN(radians) || isInfinite(radians)) {
NaN
} else {
sin(radians) / cos(radians)
}
}
// Math.gamma implemented using the Lanczos approximation
// https://en.wikipedia.org/wiki/Lanczos_approximation
/**
* Computes the gamma function of a value using Lanczos approximation.
*
* @param z: The value to interpolate
* @returns The gamma of the given value
*
* @throws InvalidArgument(String): When `z` is zero
*
* @since v0.5.4
*/
provide let rec gamma = z => {
if (z == 0) {
throw Exception.InvalidArgument("Gamma of 0 is undefined")
} else if (isInteger(z) && z > 0) {
let mut output = 1
for (let mut i = 1; i < z; i += 1) {
output *= i
}
output
} else {
let mut z = z
let g = 7
let c = [>
0.99999999999980993,
676.5203681218851,
-1259.1392167224028,
771.32342877765313,
-176.61502916214059,
12.507343278686905,
-0.13857109526572012,
9.9843695780195716e-6,
1.5056327351493116e-7,
]
let mut output = 0
if (z < 0.5) {
output = pi / (sin(pi * z) * gamma(1 - z))
} else if (z == 0.5) {
// Handle this case separately because it is out of the domain of Number.pow when calculating
output = 1.7724538509055159
} else {
z -= 1
let mut x = c[0]
for (let mut i = 1; i < g + 2; i += 1) {
x += c[i] / (z + i)
}
let t = z + g + 0.5
output = sqrt(2 * pi) * (t ** (z + 0.5)) * exp(t * -1) * x
}
if (abs(output) == Infinity) Infinity else output
}
}
/**
* Computes the product of consecutive integers for an integer input and computes the gamma function for non-integer inputs.
*
* @param n: The value to factorialize
* @returns The factorial of the given value
*
* @throws InvalidArgument(String): When `n` is negative
*
* @since v0.5.4
*/
provide let rec factorial = n => {
if (isInteger(n) && n < 0) gamma(abs(n) + 1) * -1 else if (
!isInteger(n) && n < 0
) {
throw Exception.InvalidArgument(
"Cannot compute the factorial of a negative non-integer"
)
} else {
gamma(n + 1)
}
}
/**
* Converts degrees to radians.
*
* @param degrees: The value to convert
* @returns The value in radians
*
* @since v0.5.4
*/
provide let toRadians = degrees => degrees * (pi / 180)
/**
* Converts radians to degrees.
*
* @param radians: The value to convert
* @returns The value in degrees
*
* @since v0.5.4
*/
provide let toDegrees = radians => radians * (180 / pi)
/**
* Constrains a number within the given inclusive range.
*
* @param range: The inclusive range to clamp within
* @param input: The number to clamp
* @returns The constrained number
*
* @since v0.6.0
*/
provide let clamp = (range, input) => {
if (isNaN(input)) {
input
} else {
let rangeEnd = max(range.rangeStart, range.rangeEnd)
let rangeStart = min(range.rangeStart, range.rangeEnd)
if (input > rangeEnd) rangeEnd else if (input < rangeStart) rangeStart
else input
}
}
/**
* Maps a weight between 0 and 1 within the given inclusive range.
*
* @param range: The inclusive range to interpolate within
* @param weight: The weight to interpolate
* @returns The blended value
*
* @throws InvalidArgument(String): When `weight` is not between 0 and 1
* @throws InvalidArgument(String): When `range` is not finite
* @throws InvalidArgument(String): When `range` includes NaN
*
* @since v0.6.0
*/
provide let linearInterpolate = (range, weight) => {
if (weight < 0 || weight > 1 || isNaN(weight))
throw Exception.InvalidArgument("Weight must be between 0 and 1")
if (isInfinite(range.rangeStart) || isInfinite(range.rangeEnd))
throw Exception.InvalidArgument("The range must be finite")
if (isNaN(range.rangeStart) || isNaN(range.rangeEnd))
throw Exception.InvalidArgument("The range must not include NaN")
(range.rangeEnd - range.rangeStart) * weight + range.rangeStart
}
/**
* Scales a number from one inclusive range to another inclusive range.
* If the number is outside the input range, it will be clamped.
*
* @param inputRange: The inclusive range you are mapping from
* @param outputRange: The inclusive range you are mapping to
* @param current: The number to map
* @returns The mapped number
*
* @throws InvalidArgument(String): When `inputRange` is not finite
* @throws InvalidArgument(String): When `inputRange` includes NaN
* @throws InvalidArgument(String): When `outputRange` is not finite
* @throws InvalidArgument(String): When `outputRange` includes NaN
*
* @since v0.6.0
*/
provide let linearMap = (inputRange, outputRange, current) => {
if (isNaN(current)) {
current
} else {
if (isInfinite(inputRange.rangeStart) || isInfinite(inputRange.rangeEnd))
throw Exception.InvalidArgument("The inputRange must be finite")
if (isNaN(inputRange.rangeStart) || isNaN(inputRange.rangeEnd))
throw Exception.InvalidArgument("The inputRange must not include NaN")
if (isInfinite(outputRange.rangeStart) || isInfinite(outputRange.rangeEnd))
throw Exception.InvalidArgument("The outputRange must be finite")
if (isNaN(outputRange.rangeStart) || isNaN(outputRange.rangeEnd))
throw Exception.InvalidArgument("The outputRange must not include NaN")
let mapped = (current - inputRange.rangeStart) *
(outputRange.rangeEnd - outputRange.rangeStart) /
(inputRange.rangeEnd - inputRange.rangeStart) +
outputRange.rangeStart
clamp(outputRange, mapped)
}
}