-
-
Notifications
You must be signed in to change notification settings - Fork 115
/
number.gr
928 lines (873 loc) 路 26.9 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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
/*
* ====================================================
* Applies to all functions with a comment referring here.
*
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
*
* ====================================================
*/
/**
* Utilities for working with numbers.
*
* @example from "number" include Number
*
* @since v0.4.0
*/
module Number
from "runtime/unsafe/wasmi32" include WasmI32
from "runtime/unsafe/wasmi64" include WasmI64
from "runtime/unsafe/wasmf32" include WasmF32
from "runtime/unsafe/wasmf64" include WasmF64
from "runtime/unsafe/memory" include Memory
from "runtime/dataStructures" include DataStructures
use DataStructures.{ newFloat64, allocateString }
from "runtime/numbers" include Numbers
use Numbers.{
coerceNumberToWasmF64,
reducedInteger,
isFloat,
isInteger,
isRational,
isBoxedNumber,
isNaN,
}
from "runtime/atoi/parse" include Parse as Atoi
from "runtime/atof/parse" include Parse as Atof
from "runtime/unsafe/tags" include Tags
from "runtime/exception" include Exception
/**
* 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) => {
use WasmF64.{ (==) }
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) => {
use WasmI32.{ (==) }
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) {
use WasmF64.{ (-), (==) }
// 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) => {
use WasmI32.{ (==) }
// 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) {
use WasmF64.{ (-), (==), (!=) }
let wf64 = WasmF64.load(asPtr, 8n)
wf64 - wf64 != 0.0W && wf64 == wf64
} else {
false
}
} else {
false
}
}
/**
* Determines whether two values are considered close to each other using a relative and absolute tolerance.
*
* @param a: The first value
* @param b: The second value
* @param relativeTolerance: The maximum tolerance to use relative to the larger absolute value `a` or `b`
* @param absoluteTolerance: The absolute tolerance to use, regardless of the values of `a` or `b`
* @returns `true` if the values are considered close to each other or `false` otherwise
*
* @since v0.6.0
*/
provide let isClose = (a, b, relativeTolerance=1e-9, absoluteTolerance=0.0) => {
if (a == b) {
true
} else if (isFinite(a) && isFinite(b)) {
abs(a - b) <=
max(relativeTolerance * max(abs(a), abs(b)), absoluteTolerance)
} else {
// NaN and infinities which were not equal
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
use WasmI32.{ (+), (-), 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
}
@unsafe
let rf = z => {
// see: musl/src/math/asin.c and SUN COPYRIGHT NOTICE at top of file
// Operators
use WasmF64.{ (+), (*), (/) }
/* coefficients for R(x^2) */
let pS0 = 1.66666666666666657415e-01W /* 0x3FC55555, 0x55555555 */
let pS1 = -3.25565818622400915405e-01W /* 0xBFD4D612, 0x03EB6F7D */
let pS2 = 2.01212532134862925881e-01W /* 0x3FC9C155, 0x0E884455 */
let pS3 = -4.00555345006794114027e-02W /* 0xBFA48228, 0xB5688F3B */
let pS4 = 7.91534994289814532176e-04W /* 0x3F49EFE0, 0x7501B288 */
let pS5 = 3.47933107596021167570e-05W /* 0x3F023DE1, 0x0DFDF709 */
let qS1 = -2.40339491173441421878e+00W /* 0xC0033A27, 0x1C8A2D4B */
let qS2 = 2.02094576023350569471e+00W /* 0x40002AE5, 0x9C598AC8 */
let qS3 = -6.88283971605453293030e-01W /* 0xBFE6066C, 0x1B8D0159 */
let qS4 = 7.70381505559019352791e-02W /* 0x3FB3B8C5, 0xB12E9282 */
// Calculations
let p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5)))))
let q = 1.0W + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4)))
p / q
}
/**
* Computes the inverse sine of the given angle.
*
* @param angle: A number between -1 and 1, representing the angle's sine value
* @returns The inverse sine (angle in radians between `-pi/2` and `pi/2`) of the given `angle` or `NaN` if the given `angle` is not between`-1` and `1`
*
* @since v0.6.0
*/
@unsafe
provide let asin = angle => {
// see: musl/src/math/asin.c and SUN COPYRIGHT NOTICE at top of file
let origAngle = Numbers.coerceNumberToWasmF64(angle)
let mut x = origAngle
let pio2_hi = 1.57079632679489655800e+00W /* 0x3FF921FB, 0x54442D18 */
let pio2_lo = 6.12323399573676603587e-17W /* 0x3C91A626, 0x33145C07 */
use WasmI32.{ (&), (|), leU as (<), geU as (>=) }
use WasmI64.{ (>>>) }
use WasmF64.{ (+), (-), (*), (/) }
let hx = WasmI32.wrapI64(WasmI64.reinterpretF64(x) >>> 32N)
let ix = hx & 0x7fffffffn
/* |x| >= 1 or nan */
if (ix >= 0x3ff00000n) {
let lx = WasmI32.wrapI64(WasmI64.reinterpretF64(x))
use WasmI32.{ (-) }
/* asin(1) = +-pi/2 with inexact */
if (WasmI32.eqz(ix - 0x3ff00000n | lx))
return WasmI32.toGrain(newFloat64(x * pio2_hi + 0x1p-120W)): Number
return WasmI32.toGrain(newFloat64(NaNW)): Number
}
/* |x| < 0.5 */
if (ix < 0x3fe00000n) {
/* if 0x1p-1022 <= |x| < 0x1p-26, avoid raising underflow */
let output = if (ix < 0x3e500000n && ix >= 0x00100000n)
x
else
x + x * rf(x * x)
return WasmI32.toGrain(newFloat64(output)): Number
}
/* 1 > |x| >= 0.5 */
let z = (1.0W - WasmF64.abs(x)) * 0.5W
let s = WasmF64.sqrt(z)
let r = rf(z)
/* if |x| > 0.975 */
if (ix >= 0x3fef3333n) {
x = pio2_hi - (2.0W * (s + s * r) - pio2_lo)
} else {
use WasmI64.{ (&) }
/* f+c = sqrt(z) */
let f = WasmF64.reinterpretI64(
WasmI64.reinterpretF64(s) & 0xFFFFFFFF00000000N
)
let c = (z - f * f) / (s + f)
x = 0.5W * pio2_hi -
(2.0W * s * r - (pio2_lo - 2.0W * c) - (0.5W * pio2_hi - 2.0W * f))
}
x = WasmF64.copySign(x, origAngle)
return WasmI32.toGrain(newFloat64(x)): Number
}
/**
* Computes the inverse cosine of the given angle.
*
* @param angle: A number between -1 and 1, representing the angle's cosine value
* @returns The inverse cosine (angle in radians between `-pi/2` and `pi/2`) of the given `angle` or `NaN` if the given `angle` is not between`-1` and `1`
*
* @since v0.6.0
*/
@unsafe
provide let acos = angle => {
// see: musl/src/math/acos.c and SUN COPYRIGHT NOTICE at top of file
let origAngle = Numbers.coerceNumberToWasmF64(angle)
let mut x = origAngle
let pio2_hi = 1.57079632679489655800e+00W /* 0x3FF921FB, 0x54442D18 */
let pio2_lo = 6.12323399573676603587e-17W /* 0x3C91A626, 0x33145C07 */
use WasmI32.{ (>>), (&), (|), (!=), leU as (<), geU as (>=), leU as (<=) }
use WasmI64.{ (>>>) }
use WasmF64.{ (+), (-), (*), (/) }
let hx = WasmI32.wrapI64(WasmI64.reinterpretF64(x) >>> 32N)
let ix = hx & 0x7fffffffn
/* |x| >= 1 or nan */
if (ix >= 0x3ff00000n) {
let lx = WasmI32.wrapI64(WasmI64.reinterpretF64(x))
use WasmI32.{ (-) }
if (WasmI32.eqz(ix - 0x3ff00000n | lx)) {
/* acos(1)=0, acos(-1)=pi */
if (hx >> 31n != 0n)
return WasmI32.toGrain(newFloat64(2.0W * pio2_hi + 0x1p-120W)): Number
else
return 0
}
return WasmI32.toGrain(newFloat64(NaNW)): Number
}
/* |x| < 0.5 */
if (ix < 0x3fe00000n) {
/* |x| < 2**-57 */
let output = if (ix <= 0x3c600000n)
pio2_hi + 0x1p-120W
else
pio2_hi - (x - (pio2_lo - x * rf(x * x)))
return WasmI32.toGrain(newFloat64(output)): Number
}
/* x < -0.5 */
if (hx >> 31n != 0n) {
let z = (1.0W + x) * 0.5W
let s = WasmF64.sqrt(z)
let w = rf(z) * s - pio2_lo
return WasmI32.toGrain(newFloat64(2.0W * (pio2_hi - (s + w)))): Number
}
/* x > 0.5 */
use WasmI64.{ (&) }
let z = (1.0W - x) * 0.5W
let s = WasmF64.sqrt(z)
let df = WasmF64.reinterpretI64(
WasmI64.reinterpretF64(s) & 0xFFFFFFFF00000000N
)
let c = (z - df * df) / (s + df)
let w = rf(z) * s + c
return WasmI32.toGrain(newFloat64(2.0W * (df + w))): Number
}
/**
* Computes the inverse tangent of the given angle.
*
* @param angle: A number between -1 and 1, representing the angle's tangent value
* @returns The inverse tangent (angle in radians between `-pi/2` and `pi/2`) of the given `angle` or `NaN` if the given `angle` is not between`-1` and `1`
*
* @since v0.6.0
*/
@unsafe
provide let atan = angle => {
// see: musl/src/math/asin.c and SUN COPYRIGHT NOTICE at top of file
let origAngle = Numbers.coerceNumberToWasmF64(angle)
let mut x = origAngle
// Constants
let atanhi0 = 4.63647609000806093515e-01W // atan(0.5)hi 0x3FDDAC67, 0x0561BB4F
let atanhi1 = 7.85398163397448278999e-01W // atan(1.0)hi 0x3FE921FB, 0x54442D18
let atanhi2 = 9.82793723247329054082e-01W // atan(1.5)hi 0x3FEF730B, 0xD281F69B
let atanhi3 = 1.57079632679489655800e+00W // atan(inf)hi 0x3FF921FB, 0x54442D18
let atanlo0 = 2.26987774529616870924e-17W // atan(0.5)lo 0x3C7A2B7F, 0x222F65E2
let atanlo1 = 3.06161699786838301793e-17W // atan(1.0)lo 0x3C81A626, 0x33145C07
let atanlo2 = 1.39033110312309984516e-17W // atan(1.5)lo 0x3C700788, 0x7AF0CBBD
let atanlo3 = 6.12323399573676603587e-17W // atan(inf)lo 0x3C91A626, 0x33145C07
let aT0 = 3.33333333333329318027e-01W // 0x3FD55555, 0x5555550D
let aT1 = -1.99999999998764832476e-01W // 0xBFC99999, 0x9998EBC4
let aT2 = 1.42857142725034663711e-01W // 0x3FC24924, 0x920083FF
let aT3 = -1.11111104054623557880e-01W // 0xBFBC71C6, 0xFE231671
let aT4 = 9.09088713343650656196e-02W // 0x3FB745CD, 0xC54C206E
let aT5 = -7.69187620504482999495e-02W // 0xBFB3B0F2, 0xAF749A6D
let aT6 = 6.66107313738753120669e-02W // 0x3FB10D66, 0xA0D03D51
let aT7 = -5.83357013379057348645e-02W // 0xBFADDE2D, 0x52DEFD9A
let aT8 = 4.97687799461593236017e-02W // 0x3FA97B4B, 0x24760DEB
let aT9 = -3.65315727442169155270e-02W // 0xBFA2B444, 0x2C6A6C2F
let aT10 = 1.62858201153657823623e-02W // 0x3F90AD3A, 0xE322DA11
// Operators
use WasmI32.{ (&), (<), (>=), (==) }
use WasmI64.{ (>>>) }
use WasmF64.{ (+), (-), (*), (/) }
// Calculations
let ix = WasmI32.wrapI64(WasmI64.reinterpretF64(x) >>> 32N)
let sx = x
let ix = ix & 0x7FFFFFFFn
/* if |x| >= 2^66 */
if (ix >= 0x44100000n) {
if (isNaN(angle)) return NaN
let z = atanhi3 + 0x1p-120W
return WasmI32.toGrain(newFloat64(WasmF64.copySign(z, sx))): Number
}
let mut id = 3n
/* |x| < 0.4375 */
if (ix < 0x3FDC0000n) {
/* |x| < 2^-27 */
if (ix < 0x3E400000n) return angle
id = -1n
} else {
x = WasmF64.abs(x)
/* |x| < 1.1875 */
if (ix < 0x3FF30000n) {
/* 7/16 <= |x| < 11/16 */
if (ix < 0x3FE60000n) {
id = 0n
x = (2.0W * x - 1.0W) / (2.0W + x)
} else { /* 11/16 <= |x| < 19/16 */
id = 1n
x = (x - 1.0W) / (x + 1.0W)
}
} else {
/* |x| < 2.4375 */
if (ix < 0x40038000n) {
id = 2n
x = (x - 1.5W) / (1.0W + 1.5W * x)
} else { /* 2.4375 <= |x| < 2^66 */
x = -1.0W / x
}
}
}
let z = x * x
let w = z * z
let s1 = z * (aT0 + w * (aT2 + w * (aT4 + w * (aT6 + w * (aT8 + w * aT10)))))
let s2 = w * (aT1 + w * (aT3 + w * (aT5 + w * (aT7 + w * aT9))))
let s3 = x * (s1 + s2)
use WasmI32.{ (<) }
if (id < 0n)
return WasmI32.toGrain(newFloat64(WasmF64.copySign(x - s3, sx))): Number
let mut z = 0.0W
match (id) {
0n => z = atanhi0 - (s3 - atanlo0 - x),
1n => z = atanhi1 - (s3 - atanlo1 - x),
2n => z = atanhi2 - (s3 - atanlo2 - x),
3n => z = atanhi3 - (s3 + atanlo3 - x),
_ => fail "Unreachable",
}
return WasmI32.toGrain(newFloat64(WasmF64.copySign(z, sx))): Number
}
/**
* Computes the angle between the positive x-axis and the ray from the origin to the point (x, y).
*
* @param y: The given y coordinate
* @param x: The given x coordinate
* @returns The angle in radians between the positive x-axis and the point (x, y)
*
* @example Number.atan2(0, 1) == Number.pi
*
* @since v0.6.0
*/
provide let atan2 = (y, x) => {
if (x > 0) {
atan(y / x)
} else if (x < 0 && y >= 0) {
atan(y / x) + pi
} else if (x < 0 && y < 0) {
atan(y / x) - pi
} else if (x == 0 && y > 0) {
pi / 2
} else if (x == 0 && y < 0) {
pi / -2
} else { // x == 0 && y == 0
0
}
}
/**
* 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)
}
}