-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathmath.zig
More file actions
1879 lines (1683 loc) · 73.3 KB
/
math.zig
File metadata and controls
1879 lines (1683 loc) · 73.3 KB
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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const builtin = @import("builtin");
const std = @import("std.zig");
const float = @import("math/float.zig");
const assert = std.debug.assert;
const mem = std.mem;
const testing = std.testing;
const Alignment = std.mem.Alignment;
/// Euler's number (e)
pub const e = 2.71828182845904523536028747135266249775724709369995;
/// Archimedes' constant (π)
pub const pi = 3.14159265358979323846264338327950288419716939937510;
/// Phi or Golden ratio constant (Φ) = (1 + sqrt(5))/2
pub const phi = 1.6180339887498948482045868343656381177203091798057628621;
/// Circle constant (τ)
pub const tau = 2 * pi;
/// log2(e)
pub const log2e = 1.442695040888963407359924681001892137;
/// log10(e)
pub const log10e = 0.434294481903251827651128918916605082;
/// ln(2)
pub const ln2 = 0.693147180559945309417232121458176568;
/// ln(10)
pub const ln10 = 2.302585092994045684017991454684364208;
/// 2/sqrt(π)
pub const two_sqrtpi = 1.128379167095512573896158903121545172;
/// sqrt(2)
pub const sqrt2 = 1.414213562373095048801688724209698079;
/// 1/sqrt(2)
pub const sqrt1_2 = 0.707106781186547524400844362104849039;
/// pi/180.0
pub const rad_per_deg = 0.0174532925199432957692369076848861271344287188854172545609719144;
/// 180.0/pi
pub const deg_per_rad = 57.295779513082320876798154814105170332405472466564321549160243861;
pub const Sign = enum(u1) { positive, negative };
pub const FloatRepr = float.FloatRepr;
pub const floatExponentBits = float.floatExponentBits;
pub const floatMantissaBits = float.floatMantissaBits;
pub const floatFractionalBits = float.floatFractionalBits;
pub const floatExponentMin = float.floatExponentMin;
pub const floatExponentMax = float.floatExponentMax;
pub const floatTrueMin = float.floatTrueMin;
pub const floatMin = float.floatMin;
pub const floatMax = float.floatMax;
pub const floatEps = float.floatEps;
pub const floatEpsAt = float.floatEpsAt;
pub const inf = float.inf;
pub const nan = float.nan;
pub const snan = float.snan;
/// Performs an approximate comparison of two floating point values `x` and `y`.
/// Returns true if the absolute difference between them is less or equal than
/// the specified tolerance.
///
/// The `tolerance` parameter is the absolute tolerance used when determining if
/// the two numbers are close enough; a good value for this parameter is a small
/// multiple of `floatEps(T)`.
///
/// Note that this function is recommended for comparing small numbers
/// around zero; using `approxEqRel` is suggested otherwise.
///
/// NaN values are never considered equal to any value.
pub fn approxEqAbs(comptime T: type, x: T, y: T, tolerance: T) bool {
assert(@typeInfo(T) == .float or @typeInfo(T) == .comptime_float);
assert(tolerance >= 0);
// Fast path for equal values (and signed zeros and infinites).
if (x == y)
return true;
if (isNan(x) or isNan(y))
return false;
return @abs(x - y) <= tolerance;
}
/// Performs an approximate comparison of two floating point values `x` and `y`.
/// Returns true if the absolute difference between them is less or equal than
/// `max(|x|, |y|) * tolerance`, where `tolerance` is a positive number greater
/// than zero.
///
/// The `tolerance` parameter is the relative tolerance used when determining if
/// the two numbers are close enough; a good value for this parameter is usually
/// `sqrt(floatEps(T))`, meaning that the two numbers are considered equal if at
/// least half of the digits are equal.
///
/// Note that for comparisons of small numbers around zero this function won't
/// give meaningful results, use `approxEqAbs` instead.
///
/// NaN values are never considered equal to any value.
pub fn approxEqRel(comptime T: type, x: T, y: T, tolerance: T) bool {
assert(@typeInfo(T) == .float or @typeInfo(T) == .comptime_float);
assert(tolerance > 0);
// Fast path for equal values (and signed zeros and infinites).
if (x == y)
return true;
if (isNan(x) or isNan(y))
return false;
return @abs(x - y) <= @max(@abs(x), @abs(y)) * tolerance;
}
test approxEqAbs {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime floatEps(T);
const min_value = comptime floatMin(T);
try testing.expect(approxEqAbs(T, 0.0, 0.0, eps_value));
try testing.expect(approxEqAbs(T, -0.0, -0.0, eps_value));
try testing.expect(approxEqAbs(T, 0.0, -0.0, eps_value));
try testing.expect(!approxEqAbs(T, 1.0 + 2 * eps_value, 1.0, eps_value));
try testing.expect(approxEqAbs(T, 1.0 + 1 * eps_value, 1.0, eps_value));
try testing.expect(approxEqAbs(T, min_value, 0.0, eps_value * 2));
try testing.expect(approxEqAbs(T, -min_value, 0.0, eps_value * 2));
}
comptime {
// `comptime_float` is guaranteed to have the same precision and operations of
// the largest other floating point type, which is f128 but it doesn't have a
// defined layout so we can't rely on `@bitCast` to construct the smallest
// possible epsilon value like we do in the tests above. In the same vein, we
// also can't represent a max/min, `NaN` or `Inf` values.
const eps_value = 1e-4;
try testing.expect(approxEqAbs(comptime_float, 0.0, 0.0, eps_value));
try testing.expect(approxEqAbs(comptime_float, -0.0, -0.0, eps_value));
try testing.expect(approxEqAbs(comptime_float, 0.0, -0.0, eps_value));
try testing.expect(!approxEqAbs(comptime_float, 1.0 + 2 * eps_value, 1.0, eps_value));
try testing.expect(approxEqAbs(comptime_float, 1.0 + 1 * eps_value, 1.0, eps_value));
}
}
test approxEqRel {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime floatEps(T);
const sqrt_eps_value = comptime sqrt(eps_value);
const nan_value = comptime nan(T);
const inf_value = comptime inf(T);
const min_value = comptime floatMin(T);
try testing.expect(approxEqRel(T, 1.0, 1.0, sqrt_eps_value));
try testing.expect(!approxEqRel(T, 1.0, 0.0, sqrt_eps_value));
try testing.expect(!approxEqRel(T, 1.0, nan_value, sqrt_eps_value));
try testing.expect(!approxEqRel(T, nan_value, nan_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, inf_value, inf_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, min_value, min_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, -min_value, -min_value, sqrt_eps_value));
}
comptime {
// `comptime_float` is guaranteed to have the same precision and operations of
// the largest other floating point type, which is f128 but it doesn't have a
// defined layout so we can't rely on `@bitCast` to construct the smallest
// possible epsilon value like we do in the tests above. In the same vein, we
// also can't represent a max/min, `NaN` or `Inf` values.
const eps_value = 1e-4;
const sqrt_eps_value = sqrt(eps_value);
try testing.expect(approxEqRel(comptime_float, 1.0, 1.0, sqrt_eps_value));
try testing.expect(!approxEqRel(comptime_float, 1.0, 0.0, sqrt_eps_value));
}
}
pub fn raiseInvalid() void {
// Raise INVALID fpu exception
}
pub fn raiseUnderflow() void {
// Raise UNDERFLOW fpu exception
}
pub fn raiseOverflow() void {
// Raise OVERFLOW fpu exception
}
pub fn raiseInexact() void {
// Raise INEXACT fpu exception
}
pub fn raiseDivByZero() void {
// Raise INEXACT fpu exception
}
pub const isNan = @import("math/isnan.zig").isNan;
pub const isSignalNan = @import("math/isnan.zig").isSignalNan;
pub const frexp = @import("math/frexp.zig").frexp;
pub const Frexp = @import("math/frexp.zig").Frexp;
pub const modf = @import("math/modf.zig").modf;
pub const Modf = @import("math/modf.zig").Modf;
pub const copysign = @import("math/copysign.zig").copysign;
pub const isFinite = @import("math/isfinite.zig").isFinite;
pub const isInf = @import("math/isinf.zig").isInf;
pub const isPositiveInf = @import("math/isinf.zig").isPositiveInf;
pub const isNegativeInf = @import("math/isinf.zig").isNegativeInf;
pub const isPositiveZero = @import("math/iszero.zig").isPositiveZero;
pub const isNegativeZero = @import("math/iszero.zig").isNegativeZero;
pub const isNormal = @import("math/isnormal.zig").isNormal;
pub const nextAfter = @import("math/nextafter.zig").nextAfter;
pub const signbit = @import("math/signbit.zig").signbit;
pub const scalbn = @import("math/scalbn.zig").scalbn;
pub const ldexp = @import("math/ldexp.zig").ldexp;
pub const pow = @import("math/pow.zig").pow;
pub const powi = @import("math/powi.zig").powi;
pub const sqrt = @import("math/sqrt.zig").sqrt;
pub const cbrt = @import("math/cbrt.zig").cbrt;
pub const acos = @import("math/acos.zig").acos;
pub const asin = @import("math/asin.zig").asin;
pub const atan = @import("math/atan.zig").atan;
pub const atan2 = @import("math/atan2.zig").atan2;
pub const hypot = @import("math/hypot.zig").hypot;
pub const expm1 = @import("math/expm1.zig").expm1;
pub const ilogb = @import("math/ilogb.zig").ilogb;
pub const log = @import("math/log.zig").log;
pub const log2 = @import("math/log2.zig").log2;
pub const log10 = @import("math/log10.zig").log10;
pub const log10_int = @import("math/log10.zig").log10_int;
pub const log_int = @import("math/log_int.zig").log_int;
pub const log1p = @import("math/log1p.zig").log1p;
pub const asinh = @import("math/asinh.zig").asinh;
pub const acosh = @import("math/acosh.zig").acosh;
pub const atanh = @import("math/atanh.zig").atanh;
pub const sinh = @import("math/sinh.zig").sinh;
pub const cosh = @import("math/cosh.zig").cosh;
pub const tanh = @import("math/tanh.zig").tanh;
pub const egcd = @import("math/egcd.zig").egcd;
pub const gcd = @import("math/gcd.zig").gcd;
pub const lcm = @import("math/lcm.zig").lcm;
pub const gamma = @import("math/gamma.zig").gamma;
pub const lgamma = @import("math/gamma.zig").lgamma;
/// Sine trigonometric function on a floating point number.
/// Uses a dedicated hardware instruction when available.
/// This is the same as calling the builtin @sin
pub inline fn sin(value: anytype) @TypeOf(value) {
return @sin(value);
}
/// Cosine trigonometric function on a floating point number.
/// Uses a dedicated hardware instruction when available.
/// This is the same as calling the builtin @cos
pub inline fn cos(value: anytype) @TypeOf(value) {
return @cos(value);
}
/// Tangent trigonometric function on a floating point number.
/// Uses a dedicated hardware instruction when available.
/// This is the same as calling the builtin @tan
pub inline fn tan(value: anytype) @TypeOf(value) {
return @tan(value);
}
/// Converts an angle in radians to degrees. T must be a float or comptime number or a vector of floats.
pub fn radiansToDegrees(ang: anytype) if (@TypeOf(ang) == comptime_int) comptime_float else @TypeOf(ang) {
const T = @TypeOf(ang);
switch (@typeInfo(T)) {
.float, .comptime_float, .comptime_int => return ang * deg_per_rad,
.vector => |V| if (@typeInfo(V.child) == .float) return ang * @as(T, @splat(deg_per_rad)),
else => {},
}
@compileError("Input must be float or a comptime number, or a vector of floats.");
}
test radiansToDegrees {
const zero: f32 = 0;
const half_pi: f32 = pi / 2.0;
const neg_quart_pi: f32 = -pi / 4.0;
const one_pi: f32 = pi;
const two_pi: f32 = 2.0 * pi;
try std.testing.expectApproxEqAbs(@as(f32, 0), radiansToDegrees(zero), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 90), radiansToDegrees(half_pi), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -45), radiansToDegrees(neg_quart_pi), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 180), radiansToDegrees(one_pi), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 360), radiansToDegrees(two_pi), 1e-6);
const result = radiansToDegrees(@Vector(4, f32){
half_pi,
neg_quart_pi,
one_pi,
two_pi,
});
try std.testing.expectApproxEqAbs(@as(f32, 90), result[0], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -45), result[1], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 180), result[2], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 360), result[3], 1e-6);
}
/// Converts an angle in degrees to radians. T must be a float or comptime number or a vector of floats.
pub fn degreesToRadians(ang: anytype) if (@TypeOf(ang) == comptime_int) comptime_float else @TypeOf(ang) {
const T = @TypeOf(ang);
switch (@typeInfo(T)) {
.float, .comptime_float, .comptime_int => return ang * rad_per_deg,
.vector => |V| if (@typeInfo(V.child) == .float) return ang * @as(T, @splat(rad_per_deg)),
else => {},
}
@compileError("Input must be float or a comptime number, or a vector of floats.");
}
test degreesToRadians {
const ninety: f32 = 90;
const neg_two_seventy: f32 = -270;
const three_sixty: f32 = 360;
try std.testing.expectApproxEqAbs(@as(f32, pi / 2.0), degreesToRadians(ninety), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -3 * pi / 2.0), degreesToRadians(neg_two_seventy), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 2 * pi), degreesToRadians(three_sixty), 1e-6);
const result = degreesToRadians(@Vector(3, f32){
ninety,
neg_two_seventy,
three_sixty,
});
try std.testing.expectApproxEqAbs(@as(f32, pi / 2.0), result[0], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -3 * pi / 2.0), result[1], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 2 * pi), result[2], 1e-6);
}
/// Base-e exponential function on a floating point number.
/// Uses a dedicated hardware instruction when available.
/// This is the same as calling the builtin @exp
pub inline fn exp(value: anytype) @TypeOf(value) {
return @exp(value);
}
/// Base-2 exponential function on a floating point number.
/// Uses a dedicated hardware instruction when available.
/// This is the same as calling the builtin @exp2
pub inline fn exp2(value: anytype) @TypeOf(value) {
return @exp2(value);
}
pub const complex = @import("math/complex.zig");
pub const Complex = complex.Complex;
pub const big = @import("math/big.zig");
test {
_ = floatExponentBits;
_ = floatMantissaBits;
_ = floatFractionalBits;
_ = floatExponentMin;
_ = floatExponentMax;
_ = floatTrueMin;
_ = floatMin;
_ = floatMax;
_ = floatEps;
_ = inf;
_ = nan;
_ = snan;
_ = isNan;
_ = isSignalNan;
_ = frexp;
_ = Frexp;
_ = modf;
_ = Modf;
_ = copysign;
_ = isFinite;
_ = isInf;
_ = isPositiveInf;
_ = isNegativeInf;
_ = isNormal;
_ = nextAfter;
_ = signbit;
_ = scalbn;
_ = ldexp;
_ = pow;
_ = powi;
_ = sqrt;
_ = cbrt;
_ = acos;
_ = asin;
_ = atan;
_ = atan2;
_ = hypot;
_ = expm1;
_ = ilogb;
_ = log;
_ = log2;
_ = log10;
_ = log10_int;
_ = log_int;
_ = log1p;
_ = asinh;
_ = acosh;
_ = atanh;
_ = sinh;
_ = cosh;
_ = tanh;
_ = egcd;
_ = gcd;
_ = lcm;
_ = gamma;
_ = lgamma;
_ = complex;
_ = Complex;
_ = big;
}
/// Given two types, returns the smallest one which is capable of holding the
/// full range of the minimum value.
pub fn Min(comptime A: type, comptime B: type) type {
switch (@typeInfo(A)) {
.int => |a_info| switch (@typeInfo(B)) {
.int => |b_info| if (a_info.signedness == .unsigned and b_info.signedness == .unsigned) {
if (a_info.bits < b_info.bits) {
return A;
} else {
return B;
}
},
else => {},
},
else => {},
}
return @TypeOf(@as(A, 0) + @as(B, 0));
}
/// Odd sawtooth function
/// ```
/// |
/// / | / /
/// / |/ /
/// --/----/----/--
/// / /| /
/// / / | /
/// |
/// ```
/// Limit x to the half-open interval [-r, r).
pub fn wrap(x: anytype, r: anytype) @TypeOf(x) {
const info_x = @typeInfo(@TypeOf(x));
const info_r = @typeInfo(@TypeOf(r));
if (info_x == .int and info_x.int.signedness != .signed) {
@compileError("x must be floating point, comptime integer, or signed integer.");
}
switch (info_r) {
.int => {
// in the rare usecase of r not being comptime_int or float,
// take the penalty of having an intermediary type conversion,
// otherwise the alternative is to unwind iteratively to avoid overflow
const R = comptime do: {
var info = info_r;
info.int.bits += 1;
info.int.signedness = .signed;
break :do @Type(info);
};
const radius: if (info_r.int.signedness == .signed) @TypeOf(r) else R = r;
return @intCast(@mod(x - radius, 2 * @as(R, r)) - r); // provably impossible to overflow
},
else => {
return @mod(x - r, 2 * r) - r;
},
}
}
test wrap {
// Within range
try testing.expect(wrap(@as(i32, -75), @as(i32, 180)) == -75);
try testing.expect(wrap(@as(i32, -75), @as(i32, -180)) == -75);
// Below
try testing.expect(wrap(@as(i32, -225), @as(i32, 180)) == 135);
try testing.expect(wrap(@as(i32, -225), @as(i32, -180)) == 135);
// Above
try testing.expect(wrap(@as(i32, 361), @as(i32, 180)) == 1);
try testing.expect(wrap(@as(i32, 361), @as(i32, -180)) == 1);
// One period, right limit, positive r
try testing.expect(wrap(@as(i32, 180), @as(i32, 180)) == -180);
// One period, left limit, positive r
try testing.expect(wrap(@as(i32, -180), @as(i32, 180)) == -180);
// One period, right limit, negative r
try testing.expect(wrap(@as(i32, 180), @as(i32, -180)) == 180);
// One period, left limit, negative r
try testing.expect(wrap(@as(i32, -180), @as(i32, -180)) == 180);
// Two periods, right limit, positive r
try testing.expect(wrap(@as(i32, 540), @as(i32, 180)) == -180);
// Two periods, left limit, positive r
try testing.expect(wrap(@as(i32, -540), @as(i32, 180)) == -180);
// Two periods, right limit, negative r
try testing.expect(wrap(@as(i32, 540), @as(i32, -180)) == 180);
// Two periods, left limit, negative r
try testing.expect(wrap(@as(i32, -540), @as(i32, -180)) == 180);
// Floating point
try testing.expect(wrap(@as(f32, 1.125), @as(f32, 1.0)) == -0.875);
try testing.expect(wrap(@as(f32, -127.5), @as(f32, 180)) == -127.5);
// Mix of comptime and non-comptime
var i: i32 = 1;
_ = &i;
try testing.expect(wrap(i, 10) == 1);
const limit: i32 = 180;
// Within range
try testing.expect(wrap(@as(i32, -75), limit) == -75);
// Below
try testing.expect(wrap(@as(i32, -225), limit) == 135);
// Above
try testing.expect(wrap(@as(i32, 361), limit) == 1);
}
/// Odd ramp function
/// ```
/// | _____
/// | /
/// |/
/// -------/-------
/// /|
/// _____/ |
/// |
/// ```
/// Limit val to the inclusive range [lower, upper].
pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper) {
const T = @TypeOf(val, lower, upper);
switch (@typeInfo(T)) {
.int, .float, .comptime_int, .comptime_float => assert(lower <= upper),
.vector => |vinfo| switch (@typeInfo(vinfo.child)) {
.int, .float => assert(@reduce(.And, lower <= upper)),
else => @compileError("Expected vector of ints or floats, found " ++ @typeName(T)),
},
else => @compileError("Expected an int, float or vector of one, found " ++ @typeName(T)),
}
return @max(lower, @min(val, upper));
}
test clamp {
// Within range
try testing.expect(std.math.clamp(@as(i32, -1), @as(i32, -4), @as(i32, 7)) == -1);
// Below
try testing.expect(std.math.clamp(@as(i32, -5), @as(i32, -4), @as(i32, 7)) == -4);
// Above
try testing.expect(std.math.clamp(@as(i32, 8), @as(i32, -4), @as(i32, 7)) == 7);
// Floating point
try testing.expect(std.math.clamp(@as(f32, 1.1), @as(f32, 0.0), @as(f32, 1.0)) == 1.0);
try testing.expect(std.math.clamp(@as(f32, -127.5), @as(f32, -200), @as(f32, -100)) == -127.5);
// Vector
try testing.expect(@reduce(.And, std.math.clamp(@as(@Vector(3, f32), .{ 1.4, 15.23, 28.3 }), @as(@Vector(3, f32), .{ 9.8, 13.2, 15.6 }), @as(@Vector(3, f32), .{ 15.2, 22.8, 26.3 })) == @as(@Vector(3, f32), .{ 9.8, 15.23, 26.3 })));
// Mix of comptime and non-comptime
var i: i32 = 1;
_ = &i;
try testing.expect(std.math.clamp(i, 0, 1) == 1);
}
/// Returns the product of a and b. Returns an error on overflow.
pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) {
if (T == comptime_int) return a * b;
const ov = @mulWithOverflow(a, b);
if (ov[1] != 0) return error.Overflow;
return ov[0];
}
/// Returns the sum of a and b. Returns an error on overflow.
pub fn add(comptime T: type, a: T, b: T) (error{Overflow}!T) {
if (T == comptime_int) return a + b;
const ov = @addWithOverflow(a, b);
if (ov[1] != 0) return error.Overflow;
return ov[0];
}
/// Returns a - b, or an error on overflow.
pub fn sub(comptime T: type, a: T, b: T) (error{Overflow}!T) {
if (T == comptime_int) return a - b;
const ov = @subWithOverflow(a, b);
if (ov[1] != 0) return error.Overflow;
return ov[0];
}
pub fn negate(x: anytype) !@TypeOf(x) {
return sub(@TypeOf(x), 0, x);
}
/// Shifts a left by shift_amt. Returns an error on overflow. shift_amt
/// is unsigned.
pub fn shlExact(comptime T: type, a: T, shift_amt: Log2Int(T)) !T {
if (T == comptime_int) return a << shift_amt;
const ov = @shlWithOverflow(a, shift_amt);
if (ov[1] != 0) return error.Overflow;
return ov[0];
}
/// Shifts left. Overflowed bits are truncated.
/// A negative shift amount results in a right shift.
pub fn shl(comptime T: type, a: T, shift_amt: anytype) T {
const is_shl = shift_amt >= 0;
const abs_shift_amt = @abs(shift_amt);
const casted_shift_amt = casted_shift_amt: switch (@typeInfo(T)) {
.int => |info| {
if (abs_shift_amt < info.bits) break :casted_shift_amt @as(
Log2Int(T),
@intCast(abs_shift_amt),
);
if (info.signedness == .unsigned or is_shl) return 0;
return a >> (info.bits - 1);
},
.vector => |info| {
const Child = info.child;
const child_info = @typeInfo(Child).int;
if (abs_shift_amt < child_info.bits) break :casted_shift_amt @as(
@Vector(info.len, Log2Int(Child)),
@splat(@as(Log2Int(Child), @intCast(abs_shift_amt))),
);
if (child_info.signedness == .unsigned or is_shl) return @splat(0);
return a >> @splat(child_info.bits - 1);
},
else => comptime unreachable,
};
return if (is_shl) a << casted_shift_amt else a >> casted_shift_amt;
}
test shl {
try testing.expect(shl(u8, 0b11111111, @as(usize, 3)) == 0b11111000);
try testing.expect(shl(u8, 0b11111111, @as(usize, 8)) == 0);
try testing.expect(shl(u8, 0b11111111, @as(usize, 9)) == 0);
try testing.expect(shl(u8, 0b11111111, @as(isize, -2)) == 0b00111111);
try testing.expect(shl(u8, 0b11111111, 3) == 0b11111000);
try testing.expect(shl(u8, 0b11111111, 8) == 0);
try testing.expect(shl(u8, 0b11111111, 9) == 0);
try testing.expect(shl(u8, 0b11111111, -2) == 0b00111111);
try testing.expect(shl(@Vector(1, u32), @Vector(1, u32){42}, @as(usize, 1))[0] == @as(u32, 42) << 1);
try testing.expect(shl(@Vector(1, u32), @Vector(1, u32){42}, @as(isize, -1))[0] == @as(u32, 42) >> 1);
try testing.expect(shl(@Vector(1, u32), @Vector(1, u32){42}, 33)[0] == 0);
try testing.expect(shl(i8, -1, -100) == -1);
try testing.expect(shl(i8, -1, 100) == 0);
if (builtin.cpu.arch == .hexagon and builtin.zig_backend == .stage2_llvm) return error.SkipZigTest;
try testing.expect(@reduce(.And, shl(@Vector(2, i8), .{ -1, 1 }, -100) == @Vector(2, i8){ -1, 0 }));
try testing.expect(@reduce(.And, shl(@Vector(2, i8), .{ -1, 1 }, 100) == @Vector(2, i8){ 0, 0 }));
}
/// Shifts right. Overflowed bits are truncated.
/// A negative shift amount results in a left shift.
pub fn shr(comptime T: type, a: T, shift_amt: anytype) T {
const is_shl = shift_amt < 0;
const abs_shift_amt = @abs(shift_amt);
const casted_shift_amt = casted_shift_amt: switch (@typeInfo(T)) {
.int => |info| {
if (abs_shift_amt < info.bits) break :casted_shift_amt @as(
Log2Int(T),
@intCast(abs_shift_amt),
);
if (info.signedness == .unsigned or is_shl) return 0;
return a >> (info.bits - 1);
},
.vector => |info| {
const Child = info.child;
const child_info = @typeInfo(Child).int;
if (abs_shift_amt < child_info.bits) break :casted_shift_amt @as(
@Vector(info.len, Log2Int(Child)),
@splat(@as(Log2Int(Child), @intCast(abs_shift_amt))),
);
if (child_info.signedness == .unsigned or is_shl) return @splat(0);
return a >> @splat(child_info.bits - 1);
},
else => comptime unreachable,
};
return if (is_shl) a << casted_shift_amt else a >> casted_shift_amt;
}
test shr {
try testing.expect(shr(u8, 0b11111111, @as(usize, 3)) == 0b00011111);
try testing.expect(shr(u8, 0b11111111, @as(usize, 8)) == 0);
try testing.expect(shr(u8, 0b11111111, @as(usize, 9)) == 0);
try testing.expect(shr(u8, 0b11111111, @as(isize, -2)) == 0b11111100);
try testing.expect(shr(u8, 0b11111111, 3) == 0b00011111);
try testing.expect(shr(u8, 0b11111111, 8) == 0);
try testing.expect(shr(u8, 0b11111111, 9) == 0);
try testing.expect(shr(u8, 0b11111111, -2) == 0b11111100);
try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, @as(usize, 1))[0] == @as(u32, 42) >> 1);
try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, @as(isize, -1))[0] == @as(u32, 42) << 1);
try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, 33)[0] == 0);
try testing.expect(shr(i8, -1, -100) == 0);
try testing.expect(shr(i8, -1, 100) == -1);
if (builtin.cpu.arch == .hexagon and builtin.zig_backend == .stage2_llvm) return error.SkipZigTest;
try testing.expect(@reduce(.And, shr(@Vector(2, i8), .{ -1, 1 }, -100) == @Vector(2, i8){ 0, 0 }));
try testing.expect(@reduce(.And, shr(@Vector(2, i8), .{ -1, 1 }, 100) == @Vector(2, i8){ -1, 0 }));
}
/// Rotates right. Only unsigned values can be rotated. Negative shift
/// values result in shift modulo the bit count.
pub fn rotr(comptime T: type, x: T, r: anytype) T {
if (@typeInfo(T) == .vector) {
const C = @typeInfo(T).vector.child;
if (C == u0) return @splat(0);
if (@typeInfo(C).int.signedness == .signed) {
@compileError("cannot rotate signed integers");
}
const ar: Log2Int(C) = @intCast(@mod(r, @typeInfo(C).int.bits));
return (x >> @splat(ar)) | (x << @splat(1 + ~ar));
} else if (@typeInfo(T).int.signedness == .signed) {
@compileError("cannot rotate signed integer");
} else {
if (T == u0) return 0;
if (comptime isPowerOfTwo(@typeInfo(T).int.bits)) {
const ar: Log2Int(T) = @intCast(@mod(r, @typeInfo(T).int.bits));
return x >> ar | x << (1 +% ~ar);
} else {
const ar = @mod(r, @typeInfo(T).int.bits);
return shr(T, x, ar) | shl(T, x, @typeInfo(T).int.bits - ar);
}
}
}
test rotr {
try testing.expect(rotr(u0, 0b0, @as(usize, 3)) == 0b0);
try testing.expect(rotr(u5, 0b00001, @as(usize, 0)) == 0b00001);
try testing.expect(rotr(u6, 0b000001, @as(usize, 7)) == 0b100000);
try testing.expect(rotr(u8, 0b00000001, @as(usize, 0)) == 0b00000001);
try testing.expect(rotr(u8, 0b00000001, @as(usize, 9)) == 0b10000000);
try testing.expect(rotr(u8, 0b00000001, @as(usize, 8)) == 0b00000001);
try testing.expect(rotr(u8, 0b00000001, @as(usize, 4)) == 0b00010000);
try testing.expect(rotr(u8, 0b00000001, @as(isize, -1)) == 0b00000010);
try testing.expect(rotr(u12, 0o7777, 1) == 0o7777);
try testing.expect(rotr(@Vector(1, u32), .{1}, @as(usize, 1))[0] == @as(u32, 1) << 31);
try testing.expect(rotr(@Vector(1, u32), .{1}, @as(isize, -1))[0] == @as(u32, 1) << 1);
try std.testing.expect(@reduce(.And, rotr(@Vector(2, u0), .{ 0, 0 }, @as(usize, 42)) ==
@Vector(2, u0){ 0, 0 }));
}
/// Rotates left. Only unsigned values can be rotated. Negative shift
/// values result in shift modulo the bit count.
pub fn rotl(comptime T: type, x: T, r: anytype) T {
if (@typeInfo(T) == .vector) {
const C = @typeInfo(T).vector.child;
if (C == u0) return @splat(0);
if (@typeInfo(C).int.signedness == .signed) {
@compileError("cannot rotate signed integers");
}
const ar: Log2Int(C) = @intCast(@mod(r, @typeInfo(C).int.bits));
return (x << @splat(ar)) | (x >> @splat(1 +% ~ar));
} else if (@typeInfo(T).int.signedness == .signed) {
@compileError("cannot rotate signed integer");
} else {
if (T == u0) return 0;
if (comptime isPowerOfTwo(@typeInfo(T).int.bits)) {
const ar: Log2Int(T) = @intCast(@mod(r, @typeInfo(T).int.bits));
return x << ar | x >> 1 +% ~ar;
} else {
const ar = @mod(r, @typeInfo(T).int.bits);
return shl(T, x, ar) | shr(T, x, @typeInfo(T).int.bits - ar);
}
}
}
test rotl {
try testing.expect(rotl(u0, 0b0, @as(usize, 3)) == 0b0);
try testing.expect(rotl(u5, 0b00001, @as(usize, 0)) == 0b00001);
try testing.expect(rotl(u6, 0b000001, @as(usize, 7)) == 0b000010);
try testing.expect(rotl(u8, 0b00000001, @as(usize, 0)) == 0b00000001);
try testing.expect(rotl(u8, 0b00000001, @as(usize, 9)) == 0b00000010);
try testing.expect(rotl(u8, 0b00000001, @as(usize, 8)) == 0b00000001);
try testing.expect(rotl(u8, 0b00000001, @as(usize, 4)) == 0b00010000);
try testing.expect(rotl(u8, 0b00000001, @as(isize, -1)) == 0b10000000);
try testing.expect(rotl(u12, 0o7777, 1) == 0o7777);
try testing.expect(rotl(@Vector(1, u32), .{1 << 31}, @as(usize, 1))[0] == 1);
try testing.expect(rotl(@Vector(1, u32), .{1 << 31}, @as(isize, -1))[0] == @as(u32, 1) << 30);
try std.testing.expect(@reduce(.And, rotl(@Vector(2, u0), .{ 0, 0 }, @as(usize, 42)) ==
@Vector(2, u0){ 0, 0 }));
}
/// Returns an unsigned int type that can hold the number of bits in T - 1.
/// Suitable for 0-based bit indices of T.
pub fn Log2Int(comptime T: type) type {
// comptime ceil log2
if (T == comptime_int) return comptime_int;
const bits: u16 = @typeInfo(T).int.bits;
const log2_bits = 16 - @clz(bits - 1);
return std.meta.Int(.unsigned, log2_bits);
}
/// Returns an unsigned int type that can hold the number of bits in T.
pub fn Log2IntCeil(comptime T: type) type {
// comptime ceil log2
if (T == comptime_int) return comptime_int;
const bits: u16 = @typeInfo(T).int.bits;
const log2_bits = 16 - @clz(bits);
return std.meta.Int(.unsigned, log2_bits);
}
/// Returns the smallest integer type that can hold both from and to.
pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) type {
assert(from <= to);
const signedness: std.builtin.Signedness = if (from < 0) .signed else .unsigned;
return @Type(.{ .int = .{
.signedness = signedness,
.bits = @as(u16, @intFromBool(signedness == .signed)) +
switch (if (from < 0) @max(@abs(from) - 1, to) else to) {
0 => 0,
else => |pos_max| 1 + log2(pos_max),
},
} });
}
test IntFittingRange {
try testing.expect(IntFittingRange(0, 0) == u0);
try testing.expect(IntFittingRange(0, 1) == u1);
try testing.expect(IntFittingRange(0, 2) == u2);
try testing.expect(IntFittingRange(0, 3) == u2);
try testing.expect(IntFittingRange(0, 4) == u3);
try testing.expect(IntFittingRange(0, 7) == u3);
try testing.expect(IntFittingRange(0, 8) == u4);
try testing.expect(IntFittingRange(0, 9) == u4);
try testing.expect(IntFittingRange(0, 15) == u4);
try testing.expect(IntFittingRange(0, 16) == u5);
try testing.expect(IntFittingRange(0, 17) == u5);
try testing.expect(IntFittingRange(0, 4095) == u12);
try testing.expect(IntFittingRange(2000, 4095) == u12);
try testing.expect(IntFittingRange(0, 4096) == u13);
try testing.expect(IntFittingRange(2000, 4096) == u13);
try testing.expect(IntFittingRange(0, 4097) == u13);
try testing.expect(IntFittingRange(2000, 4097) == u13);
try testing.expect(IntFittingRange(0, 123456789123456798123456789) == u87);
try testing.expect(IntFittingRange(0, 123456789123456798123456789123456789123456798123456789) == u177);
try testing.expect(IntFittingRange(-1, -1) == i1);
try testing.expect(IntFittingRange(-1, 0) == i1);
try testing.expect(IntFittingRange(-1, 1) == i2);
try testing.expect(IntFittingRange(-2, -2) == i2);
try testing.expect(IntFittingRange(-2, -1) == i2);
try testing.expect(IntFittingRange(-2, 0) == i2);
try testing.expect(IntFittingRange(-2, 1) == i2);
try testing.expect(IntFittingRange(-2, 2) == i3);
try testing.expect(IntFittingRange(-1, 2) == i3);
try testing.expect(IntFittingRange(-1, 3) == i3);
try testing.expect(IntFittingRange(-1, 4) == i4);
try testing.expect(IntFittingRange(-1, 7) == i4);
try testing.expect(IntFittingRange(-1, 8) == i5);
try testing.expect(IntFittingRange(-1, 9) == i5);
try testing.expect(IntFittingRange(-1, 15) == i5);
try testing.expect(IntFittingRange(-1, 16) == i6);
try testing.expect(IntFittingRange(-1, 17) == i6);
try testing.expect(IntFittingRange(-1, 4095) == i13);
try testing.expect(IntFittingRange(-4096, 4095) == i13);
try testing.expect(IntFittingRange(-1, 4096) == i14);
try testing.expect(IntFittingRange(-4097, 4095) == i14);
try testing.expect(IntFittingRange(-1, 4097) == i14);
try testing.expect(IntFittingRange(-1, 123456789123456798123456789) == i88);
try testing.expect(IntFittingRange(-1, 123456789123456798123456789123456789123456798123456789) == i178);
}
test "overflow functions" {
try testOverflow();
try comptime testOverflow();
}
fn testOverflow() !void {
try testing.expect((mul(i32, 3, 4) catch unreachable) == 12);
try testing.expect((add(i32, 3, 4) catch unreachable) == 7);
try testing.expect((sub(i32, 3, 4) catch unreachable) == -1);
try testing.expect((shlExact(i32, 0b11, 4) catch unreachable) == 0b110000);
}
/// Divide numerator by denominator, rounding toward zero. Returns an
/// error on overflow or when denominator is zero.
pub fn divTrunc(comptime T: type, numerator: T, denominator: T) !T {
@setRuntimeSafety(false);
if (denominator == 0) return error.DivisionByZero;
if (@typeInfo(T) == .int and @typeInfo(T).int.signedness == .signed and numerator == minInt(T) and denominator == -1) return error.Overflow;
return @divTrunc(numerator, denominator);
}
test divTrunc {
try testDivTrunc();
try comptime testDivTrunc();
}
fn testDivTrunc() !void {
try testing.expect((divTrunc(i32, 5, 3) catch unreachable) == 1);
try testing.expect((divTrunc(i32, -5, 3) catch unreachable) == -1);
try testing.expectError(error.DivisionByZero, divTrunc(i8, -5, 0));
try testing.expectError(error.Overflow, divTrunc(i8, -128, -1));
try testing.expect((divTrunc(f32, 5.0, 3.0) catch unreachable) == 1.0);
try testing.expect((divTrunc(f32, -5.0, 3.0) catch unreachable) == -1.0);
}
/// Divide numerator by denominator, rounding toward negative
/// infinity. Returns an error on overflow or when denominator is
/// zero.
pub fn divFloor(comptime T: type, numerator: T, denominator: T) !T {
@setRuntimeSafety(false);
if (denominator == 0) return error.DivisionByZero;
if (@typeInfo(T) == .int and @typeInfo(T).int.signedness == .signed and numerator == minInt(T) and denominator == -1) return error.Overflow;
return @divFloor(numerator, denominator);
}
test divFloor {
try testDivFloor();
try comptime testDivFloor();
}
fn testDivFloor() !void {
try testing.expect((divFloor(i32, 5, 3) catch unreachable) == 1);
try testing.expect((divFloor(i32, -5, 3) catch unreachable) == -2);
try testing.expectError(error.DivisionByZero, divFloor(i8, -5, 0));
try testing.expectError(error.Overflow, divFloor(i8, -128, -1));
try testing.expect((divFloor(f32, 5.0, 3.0) catch unreachable) == 1.0);
try testing.expect((divFloor(f32, -5.0, 3.0) catch unreachable) == -2.0);
}
/// Divide numerator by denominator, rounding toward positive
/// infinity. Returns an error on overflow or when denominator is
/// zero.
pub fn divCeil(comptime T: type, numerator: T, denominator: T) !T {
@setRuntimeSafety(false);
if (denominator == 0) return error.DivisionByZero;
const info = @typeInfo(T);
switch (info) {
.comptime_float, .float => return @ceil(numerator / denominator),
.comptime_int, .int => {
if (numerator < 0 and denominator < 0) {
if (info == .int and numerator == minInt(T) and denominator == -1)
return error.Overflow;
return @divFloor(numerator + 1, denominator) + 1;
}
if (numerator > 0 and denominator > 0)
return @divFloor(numerator - 1, denominator) + 1;
return @divTrunc(numerator, denominator);
},
else => @compileError("divCeil unsupported on " ++ @typeName(T)),
}
}
test divCeil {
try testDivCeil();
try comptime testDivCeil();
}
fn testDivCeil() !void {
try testing.expectEqual(@as(i32, 2), divCeil(i32, 5, 3) catch unreachable);
try testing.expectEqual(@as(i32, -1), divCeil(i32, -5, 3) catch unreachable);
try testing.expectEqual(@as(i32, -1), divCeil(i32, 5, -3) catch unreachable);
try testing.expectEqual(@as(i32, 2), divCeil(i32, -5, -3) catch unreachable);
try testing.expectEqual(@as(i32, 0), divCeil(i32, 0, 5) catch unreachable);
try testing.expectEqual(@as(u32, 0), divCeil(u32, 0, 5) catch unreachable);
try testing.expectError(error.DivisionByZero, divCeil(i8, -5, 0));
try testing.expectError(error.Overflow, divCeil(i8, -128, -1));
try testing.expectEqual(@as(f32, 0.0), divCeil(f32, 0.0, 5.0) catch unreachable);
try testing.expectEqual(@as(f32, 2.0), divCeil(f32, 5.0, 3.0) catch unreachable);
try testing.expectEqual(@as(f32, -1.0), divCeil(f32, -5.0, 3.0) catch unreachable);
try testing.expectEqual(@as(f32, -1.0), divCeil(f32, 5.0, -3.0) catch unreachable);
try testing.expectEqual(@as(f32, 2.0), divCeil(f32, -5.0, -3.0) catch unreachable);
try testing.expectEqual(6, divCeil(comptime_int, 23, 4) catch unreachable);
try testing.expectEqual(-5, divCeil(comptime_int, -23, 4) catch unreachable);
try testing.expectEqual(-5, divCeil(comptime_int, 23, -4) catch unreachable);
try testing.expectEqual(6, divCeil(comptime_int, -23, -4) catch unreachable);
try testing.expectError(error.DivisionByZero, divCeil(comptime_int, 23, 0));
try testing.expectEqual(6.0, divCeil(comptime_float, 23.0, 4.0) catch unreachable);
try testing.expectEqual(-5.0, divCeil(comptime_float, -23.0, 4.0) catch unreachable);
try testing.expectEqual(-5.0, divCeil(comptime_float, 23.0, -4.0) catch unreachable);
try testing.expectEqual(6.0, divCeil(comptime_float, -23.0, -4.0) catch unreachable);
try testing.expectError(error.DivisionByZero, divCeil(comptime_float, 23.0, 0.0));
}
/// Divide numerator by denominator. Return an error if quotient is
/// not an integer, denominator is zero, or on overflow.
pub fn divExact(comptime T: type, numerator: T, denominator: T) !T {
@setRuntimeSafety(false);
if (denominator == 0) return error.DivisionByZero;
if (@typeInfo(T) == .int and @typeInfo(T).int.signedness == .signed and numerator == minInt(T) and denominator == -1) return error.Overflow;
const result = @divTrunc(numerator, denominator);
if (result * denominator != numerator) return error.UnexpectedRemainder;
return result;
}
test divExact {
try testDivExact();
try comptime testDivExact();
}
fn testDivExact() !void {
try testing.expect((divExact(i32, 10, 5) catch unreachable) == 2);
try testing.expect((divExact(i32, -10, 5) catch unreachable) == -2);
try testing.expectError(error.DivisionByZero, divExact(i8, -5, 0));
try testing.expectError(error.Overflow, divExact(i8, -128, -1));
try testing.expectError(error.UnexpectedRemainder, divExact(i32, 5, 2));
try testing.expect((divExact(f32, 10.0, 5.0) catch unreachable) == 2.0);
try testing.expect((divExact(f32, -10.0, 5.0) catch unreachable) == -2.0);
try testing.expectError(error.UnexpectedRemainder, divExact(f32, 5.0, 2.0));