-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfixed.py
executable file
·901 lines (844 loc) · 28.7 KB
/
fixed.py
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
import decimal as dec
import math
class Fixed:
"""
Fixed-point numbers, represented using integers that store multiples
of 2^-BITS. They are not necessarily faster than floating-point numbers, nor
do they necessarily have the same precision or resolution of floating-point
numbers. The main benefit of fixed-point numbers is that they improve
determinism for applications that rely on noninteger real numbers (notably
simulations and machine learning applications), in the sense that the operations
given here deliver the same answer for the same input across computers,
whereas floating-point numbers have a host of problems that make repeatable
results difficult, including differences in their implementation, rounding
behavior, and order of operations, as well as nonassociativity of
floating-point numbers.
The operations given here are not guaranteed to be "constant-time"
(nondata-dependent and branchless) for every relevant input.
Any copyright to this file is released to the Public Domain. In case this is not
possible, this file is also licensed under Creative Commons Zero version 1.0.
"""
""" Number of bits in the fractional part of a fixed-point number. """
BITS = 20
MASK = (1 << BITS) - 1
HALF = 1 << (BITS - 1)
ArcTanTable = [
421657428,
248918914,
131521918,
66762579,
33510843,
16771757,
8387925,
4194218,
2097141,
1048574,
524287,
262143,
131071,
65535,
32767,
16384,
8192,
4096,
2048,
1024,
512,
256,
128,
64,
32,
16,
8,
4,
2,
1,
]
ArcTanHTable = [
0,
294906490,
137123709,
67461703,
33598225,
16782680,
8389290,
4194389,
2097162,
1048577,
524288,
262144,
131072,
65536,
32768,
16384,
8192,
4096,
2048,
1024,
512,
256,
128,
64,
32,
16,
8,
4,
2,
1,
]
ArcTanFrac = 29
ArcTanBitDiff = ArcTanFrac - BITS
PiArcTanBits = 1686629713 # Pi, expressed in ArcTanFrac fractional bits
TwoTimesPiArcTanBits = 3373259426 # Pi*2, expressed in ArcTanFrac fractional bits
HalfPiArcTanBits = 843314856 # Pi/2, expressed in ArcTanFrac fractional bits
SinCosK = 326016435 # Expressed in ArcTanFrac fractional bits
ExpK = 648270061 # Expressed in ArcTanFrac fractional bits
HalfPiBits = 1647099 # Half of pi, expressed in 20 fractional bits
QuarterPiArcTanBits = 421657428 # Pi/4, expressed in ArcTanFrac fractional bits
PiBits = 3294199 # Pi, expressed in 20 fractional bits
TwoTimesPiBits = 6588397 # Pi*2, expressed in 20 fractional bits
Ln2ArcTanBits = 372130559 # Ln(2), expressed in ArcTanFrac fractional bits
def __init__(self, i):
self.value = i
@staticmethod
def v(i):
"""
Converts a string, integer, Decimal, or other number type into
a fixed-point number. If the parameter is a Fixed, returns itself.
If the given number is a noninteger, returns the closest value to
a Fixed after rounding using the round-to-nearest-ties-to-even
rounding mode. The parameter is recommended to be a string
or integer, and is not recommended to be a `float`.
"""
if i.__class__ == Fixed:
return i
b = 0
neg = False
if i.__class__ == int:
neg = i < 0
b = abs(i) * (1 << Fixed.BITS)
return Fixed(-b) if neg else Fixed(b)
else:
d = dec.Decimal(i)
neg = d < 0
b = abs(dec.Decimal(i)) * (1 << Fixed.BITS)
b = int(b.quantize(dec.Decimal(1), rounding=dec.ROUND_HALF_EVEN))
return Fixed(-b) if neg else Fixed(b)
def __add__(a, b):
av = Fixed.v(a).value
bv = Fixed.v(b).value
if (av >= 0) == (bv >= 0):
return Fixed(av + bv)
if a >= 0: # a is nonnegative and b is negative
return Fixed(av - abs(bv))
else: # a is negative and b is nonnegative
return Fixed(bv - abs(av))
def __sub__(a, b):
return a + (-b)
def __mul__(a, b):
av = Fixed.v(a).value
bv = Fixed.v(b).value
ava = abs(av)
bva = abs(bv)
ret = ava * bva
frac = ret & Fixed.MASK
ret = ret >> Fixed.BITS
# Rounding to nearest, ties to even
if frac > Fixed.HALF or (frac == Fixed.HALF and (ret & 1) == 1):
ret += 1
if (av >= 0) != (bv >= 0):
ret = -ret
return Fixed(ret)
@staticmethod
def _roundedshiftraw(a, shift):
aa = abs(a)
ret = aa >> shift
frac = aa & ((1 << shift) - 1)
# Divisor's least significant bit is even
if frac > (1 << (shift - 1)) or (frac == (1 << (shift - 1)) and (ret & 1) == 1):
ret += 1
if a < 0:
ret = -ret
return ret
@staticmethod
def _roundedshift(a, shift):
return Fixed(Fixed._roundedshiftraw(a, shift))
@staticmethod
def _divbits(av, bv, outputFracBits):
"""
Divides two fixed point numbers and rounds the result
using round-to-nearest, ties to even.
av, bv - Fixed-point numbers with the same number of fractional bits
outputFracBits - Number of fractional bits in the result
"""
ava = abs(av)
bva = abs(bv)
ret = ava << outputFracBits
# Note: ret and bva are nonnegative, avoiding
# differences in rounding between languages
# when one but not both is negative
frac = ret % bva
ret = ret // bva
# Rounding to nearest, ties to even
if (bva & 1) == 0:
# Divisor's least significant bit is even
if frac > (bva >> 1) or (frac == (bva >> 1) and (ret & 1) == 1):
ret += 1
else:
if frac > (bva >> 1):
ret += 1
if (av >= 0) != (bv >= 0):
ret = -ret
return ret
@staticmethod
def _div(a, b):
av = Fixed.v(a).value
bv = Fixed.v(b).value
ret = Fixed._divbits(av, bv, Fixed.BITS)
return Fixed(ret)
def __rtruediv__(a, b):
return Fixed._div(a, b)
def __rdiv__(a, b):
return Fixed._div(a, b)
def __div__(a, b):
return Fixed._div(a, b)
def __truediv__(a, b):
return Fixed._div(a, b)
def __floordiv__(a, b):
av = Fixed.v(a).value
bv = Fixed.v(b).value
ava = abs(av)
bva = abs(bv) << Fixed.BITS
ret = ava << Fixed.BITS
oldret = ret
# Note: ret and bva are nonnegative, avoiding
# differences in rounding between languages
# when one but not both is negative
ret = ret // bva
if (av >= 0) != (bv >= 0):
frac = oldret % bva
if frac != 0:
ret += 1
ret = -ret
return Fixed.v(ret)
def __mod__(a, b):
# Note: In Python, the "//" integer division operator
# does a floor rounding of the quotient. Other programming
# languages, such as Java, truncate the fractional part of the result of division
# in integer division and define remainder, in general,
# as "a-(a/b)*b" where "/" is their integer division operator.
# Here, we use Python's definition of the "%" operator
# (and by extension "__mod__").
return a - (a // b) * b
def __neg__(self):
return Fixed(-self.value)
def __pos__(self):
return self
def __abs__(self):
return Fixed(abs(self.value))
def __lt__(self, other):
return self.value < Fixed.v(other).value
def __le__(self, other):
return self.value <= Fixed.v(other).value
def __eq__(self, other):
return self.value == Fixed.v(other).value
def __ne__(self, other):
return self.value != Fixed.v(other).value
def __gt__(self, other):
return self.value > Fixed.v(other).value
def __ge__(self, other):
return self.value >= Fixed.v(other).value
def __cmp__(self, other):
othervalue = Fixed.v(other).value
if self.value == othervalue:
return 0
if self.value < othervalue:
return -1
return 1
def floor(a):
av = Fixed.v(a)
if av >= 0:
return Fixed((av.value >> Fixed.BITS) << Fixed.BITS)
ava = abs(av.value)
if (ava & Fixed.MASK) != 0:
return Fixed(-(((ava >> Fixed.BITS) + 1) << Fixed.BITS))
else:
return av
def asin(a):
"""
Calculates an approximation of the inverse sine of the given number.
"""
av = Fixed.v(a)
if av < -1 or av > 1:
raise ValueError
return av.atan2((Fixed.v(1) - av * av).sqrt())
def acos(a):
"""
Calculates an approximation of the inverse cosine of the given number.
"""
av = Fixed.v(a)
if av < -1 or av > 1:
raise ValueError
return (Fixed.v(1) - av * av).sqrt().atan2(av)
def sqrt(a):
"""
Calculates an approximation of the square root of the given number.
"""
return Fixed.v(a).pow(Fixed(Fixed.HALF))
def __int__(a):
av = Fixed.v(a).value
ava = abs(av)
ret = ava
frac = ret & Fixed.MASK
ret = ret >> Fixed.BITS
if av < 0:
ret = -ret
return ret
def __float__(a):
fbits = 1 << Fixed.BITS
try:
return float(a.value / fbits)
except:
return float("-inf") if a < 0 else float("inf")
def round(a):
av = Fixed.v(a).value
ava = abs(av)
ret = ava
frac = ret & Fixed.MASK
ret = ret >> Fixed.BITS
# Rounding to nearest, ties away from zero
if frac >= Fixed.HALF:
ret += 1
if av < 0:
ret = -ret
return Fixed.v(ret)
# High-resolution approximation of pi/2
HalfPiHighRes = 0x1921FB54442D18469898CC51701B83
# High-resolution approximation of pi*2
TwoTimesPiHighRes = 0x6487ED5110B4611A62633145C06E0E
# Pi*3/2
PiAndHalfHighRes = 0x4B65F1FCCC8748D3C9CA64F450528A
# Pi
PiHighRes = 0x3243F6A8885A308D313198A2E03707
# Number of fractional bits in halfPiHighRes
HighResFrac = 116
@staticmethod
def _highResSine(angle):
# For angles close to pi/2 or pi*3/2.
negra = angle < 0
negOutput = negra
angle = abs(angle)
if angle >= Fixed.TwoTimesPiHighRes:
angle = angle % Fixed.TwoTimesPiHighRes
if angle >= Fixed.PiHighRes:
negOutput = not negra
if angle >= Fixed.HalfPiHighRes and angle < Fixed.PiAndHalfHighRes:
angle = abs(Fixed.PiHighRes - angle)
if angle >= Fixed.PiAndHalfHighRes:
angle = Fixed.TwoTimesPiHighRes - angle
zpidiff = angle - Fixed.HalfPiHighRes
zpidiffsq = zpidiff * zpidiff
zpidiff = zpidiffsq
zpdfrac = Fixed.HighResFrac * 2
outputbits = Fixed.ArcTanFrac * 3
ret = 1 << outputbits
ret -= Fixed._divbits(zpidiff, 2 << zpdfrac, outputbits)
denom = 24
facinput = 4
pos = True
while True:
zpidiff *= zpidiffsq
zpdfrac += Fixed.HighResFrac * 2
term = Fixed._divbits(zpidiff, denom << zpdfrac, outputbits)
if term == 0:
break
if pos:
ret += term
else:
ret -= term
pos = not pos
denom *= facinput * (facinput + 1)
facinput += 2
if negOutput:
ret = -ret
return ret
@staticmethod
def _highResCosine(angle):
# For angles close to pi/2 or pi*3/2.
ra = abs(angle)
negOutput = False
if angle >= Fixed.TwoTimesPiHighRes:
angle = angle % Fixed.TwoTimesPiHighRes
if angle >= Fixed.HalfPiHighRes and angle < Fixed.PiAndHalfHighRes:
negOutput = True
if angle >= Fixed.HalfPiHighRes and angle < Fixed.PiAndHalfHighRes:
angle = abs(Fixed.PiHighRes - angle)
if angle >= Fixed.PiAndHalfHighRes:
angle = Fixed.TwoTimesPiHighRes - angle
zpidiff = angle - Fixed.HalfPiHighRes
zpidiffsq = zpidiff * zpidiff
zpdfrac = Fixed.HighResFrac
outputbits = Fixed.ArcTanFrac * 3
ret = -Fixed._divbits(zpidiff, 1 << zpdfrac, outputbits)
denom = 6
facinput = 4
pos = True
while True:
zpidiff *= zpidiffsq
zpdfrac += Fixed.HighResFrac * 2
term = Fixed._divbits(zpidiff, denom << zpdfrac, outputbits)
if term == 0:
break
if pos:
ret += term
else:
ret -= term
pos = not pos
denom *= facinput * (facinput + 1)
facinput += 2
if negOutput:
ret = -ret
return ret
@staticmethod
def _sincos(ra):
if ra == 0:
return [0, 1 << Fixed.ArcTanFrac]
negra = ra < 0
ra = abs(ra)
if ra >= Fixed.TwoTimesPiArcTanBits:
ra = ra % Fixed.TwoTimesPiArcTanBits
pi15 = Fixed.PiArcTanBits + Fixed.HalfPiArcTanBits
negateSin = negra
negateCos = False
if ra >= Fixed.HalfPiArcTanBits and ra < pi15:
negateCos = True
ra = Fixed.PiArcTanBits - ra
if ra >= pi15:
negateSin = not negra
ra = Fixed.TwoTimesPiArcTanBits - ra
ry = 0
rx = Fixed.SinCosK
rz = ra
for i in range(len(Fixed.ArcTanTable)):
x = rx >> i
y = ry >> i
if rz >= 0:
rx -= y
ry += x
rz -= Fixed.ArcTanTable[i]
else:
rx += y
ry -= x
rz += Fixed.ArcTanTable[i]
if negateSin:
ry = -ry
if negateCos:
rx = -rx
return [ry, rx]
@staticmethod
def _signedshift(x, shift):
if x < 0:
return -((-x) << shift)
else:
return x << shift
def sin(a):
"""
Calculates the approximate sine of the given angle; the angle is in radians.
For the fraction size used by this class, this method is accurate to within
1 unit in the last place of the correctly rounded result for every input
in the range [-pi*2, pi*2].
This method's accuracy decreases beyond that range.
"""
ra = Fixed.v(a).value
if ra == 0:
return Fixed.v(0)
ret = Fixed._sincos(Fixed._signedshift(ra, Fixed.ArcTanBitDiff))[0]
return Fixed._roundedshift(ret, Fixed.ArcTanBitDiff)
def cos(a):
"""
Calculates the approximate cosine of the given angle; the angle is in radians.
For the fraction size used by this class, this method is accurate to within
1 unit in the last place of the correctly rounded result for every input
in the range [-pi*2, pi*2].
This method's accuracy decreases beyond that range.
"""
ra = Fixed.v(a).value
if ra == 0:
return Fixed.v(1)
ret = Fixed._sincos(Fixed._signedshift(ra, Fixed.ArcTanBitDiff))[1]
return Fixed._roundedshift(ret, Fixed.ArcTanBitDiff)
@staticmethod
def _tan(ra, outputbits):
if ra == 0:
return 0
sc = Fixed._sincos(ra)
ret = Fixed._divbits(sc[0], sc[1], outputbits)
if (abs(ret) >> outputbits) > 5:
# Try for more accuracy in case of high tan value
shift = Fixed.HighResFrac - Fixed.ArcTanFrac
rs = Fixed._signedshift(ra, shift)
hsin = Fixed._highResSine(rs)
hcos = Fixed._highResCosine(rs)
ret = Fixed._divbits(hsin, hcos, outputbits)
return ret
def tan(a):
"""
Calculates the approximate tangent of the given angle; the angle is in radians.
For the fraction size used by this class, this method is accurate to within
2 units in the last place of the correctly rounded result for every input
in the range [-pi*2, pi*2].
This method's accuracy decreases beyond that range.
"""
ra = Fixed.v(a).value
if ra == 0:
return Fixed.v(0)
rashft = Fixed._signedshift(ra, Fixed.ArcTanBitDiff)
return Fixed(Fixed._tan(rashft, Fixed.BITS))
def atan2(y, x):
"""
Calculates the approximate measure, in radians, of the angle formed by the
x-axis and a line determined by the origin and the given coordinates of a 2D
point. This is also known as the inverse tangent.
"""
rx = Fixed.v(x).value
ry = Fixed.v(y).value
if ry == 0 and rx == 0:
return 0
if ry == 0 and rx < 0:
return Fixed(Fixed.PiBits)
if rx == 0:
if ry >= 0:
return Fixed(Fixed.HalfPiBits)
else:
return Fixed(-Fixed.HalfPiBits)
rz = 0
xneg = rx < 0
yneg = ry < 0
rx = abs(rx) << Fixed.ArcTanBitDiff
ry = abs(ry) << Fixed.ArcTanBitDiff
for i in range(len(Fixed.ArcTanTable)):
x = rx >> i
y = ry >> i
if ry <= 0:
rx -= y
ry += x
rz -= Fixed.ArcTanTable[i]
else:
rx += y
ry -= x
rz += Fixed.ArcTanTable[i]
if yneg != xneg:
rz = -rz
if xneg:
if yneg:
rz -= Fixed.PiArcTanBits
else:
rz += Fixed.PiArcTanBits
return Fixed._roundedshift(rz, Fixed.ArcTanBitDiff)
def pow(a, b):
"""
Calculates an approximation of this number raised to the power of another number.
"""
av = Fixed.v(a)
bv = Fixed.v(b)
if bv == 0:
return Fixed.v(1)
if av == 0:
if bv < 0:
raise ValueError
return av
if av == 1:
return av
if bv.value == Fixed.HALF:
# Square root special case
ava = av.value * (1 << Fixed.BITS)
sx = ava
powerBits = 0
while sx > 0:
sx >>= 1
powerBits += 1
powerBits = (powerBits + 1) // 2
sx = ava
sy = 1 << powerBits
guardBits = Fixed.BITS // 2
while True:
sx = sy
sy = Fixed._divbits(ava, sx, guardBits)
sy += sx << guardBits
sy = Fixed._roundedshiftraw(sy, guardBits + 1)
if sy >= sx:
break
return Fixed(sx)
bvint = bv.floor() == bv
if av < 0 and not bvint:
raise ValueError
bva = abs(bv)
intpart = bva.floor()
fracpart = bva - intpart
# Power is an integer or greater than 1
if bvint or bv > 1:
r = 1 << Fixed.BITS
eiv = abs(av.value)
eivprec = Fixed.BITS
rprec = 0
# Find the power of the integer part
p = int(intpart)
while p > 0:
if (p & 1) != 0:
r *= eiv
rprec += eivprec
p >>= 1
if p != 0:
eiv *= eiv
eivprec += eivprec
if bv < 0:
# Reciprocal
rv = Fixed._divbits(1 << (rprec + Fixed.BITS), r, Fixed.BITS)
r = Fixed(rv)
else:
if bv > 1:
# We've found the power of the integer part,
# now find the power of the fractional part and
# multiply
# 'fracr' has 'rprec+BITS' fractional bits
fracr = av.pow(fracpart).value << rprec
# 'r' has 'rprec+BITS' fractional bits
r *= fracr
r = Fixed._roundedshift(r, rprec * 2 + Fixed.BITS)
else:
# 'r' has 'rprec+BITS' fractional bits; after the
# shift, it has BITS fractional bits
r = Fixed._roundedshift(r, rprec)
if av < 0 and (int(bva) & 1) == 1:
r = -r
return r
return (bv * av.log()).exp()
LogMin = (1 << BITS) * 15 // 100 # In BITS fractional bits
Log2Bits = 726817 # log(2), in BITS fractional bits
def log(a):
"""
Calculates an approximation of the natural logarithm of this number.
"""
fa = Fixed.v(a)
av = fa.value
if av <= 0:
raise ValueError
if av >= 1 << (Fixed.BITS - 1):
return (fa / 2).log() + Fixed(Fixed.Log2Bits)
if av < Fixed.LogMin:
return (fa * 2).log() - Fixed(Fixed.Log2Bits)
avx = av << Fixed.ArcTanBitDiff
rx = avx + (1 << Fixed.ArcTanFrac)
ry = avx - (1 << Fixed.ArcTanFrac)
rz = 0
for i in range(1, len(Fixed.ArcTanHTable)):
iters = 2 if i == 4 or i == 13 else 1
for m in range(iters):
x = rx >> i
y = ry >> i
if ry <= 0:
rx += y
ry += x
rz -= Fixed.ArcTanHTable[i]
else:
rx -= y
ry -= x
rz += Fixed.ArcTanHTable[i]
return Fixed._roundedshift(rz, Fixed.ArcTanBitDiff - 1)
@staticmethod
def _expinternal(avArcTanBits, recip, shift):
rx = Fixed.ExpK
ry = Fixed.ExpK
rz = avArcTanBits
for i in range(1, len(Fixed.ArcTanHTable)):
iters = 2 if i == 4 or i == 13 else 1
for m in range(iters):
x = rx >> i
y = ry >> i
if rz >= 0:
rx += y
ry += x
rz -= Fixed.ArcTanHTable[i]
else:
rx -= y
ry -= x
rz += Fixed.ArcTanHTable[i]
rx <<= shift
if recip:
# Reciprocal
rx = Fixed._divbits(1 << (Fixed.ArcTanFrac), rx, Fixed.ArcTanFrac)
return Fixed._roundedshiftraw(rx, Fixed.ArcTanBitDiff)
def exp(a):
"""
Calculates an approximation of e (base of natural logarithms) raised
to the power of this number. May raise an error if this number
is extremely high.
"""
fa = Fixed.v(a)
av = fa.value
if av == 0:
return Fixed.v(1)
if Fixed.BITS < 6 and fa < -6:
return Fixed(0)
# With BITS 6 or greater, e^-BITS will round to 0
# in the round-to-nearest mode
if Fixed.BITS >= 6 and fa < -Fixed.BITS:
return Fixed(0)
avneg = av < 0
ava = abs(av) << Fixed.ArcTanBitDiff
if abs(fa) > Fixed.v(1):
# Note: ava is nonnegative, avoiding
# differences in rounding between languages
# when one but not both is negative
fint = ava // Fixed.Ln2ArcTanBits
frac = ava - fint * Fixed.Ln2ArcTanBits
if fint > (1 << 32):
# Result too big to handle sanely
raise ValueError
avr = Fixed._expinternal(frac, avneg, fint)
return Fixed(avr)
avr = Fixed._expinternal(ava, avneg, 0)
return Fixed(avr)
def __str__(self):
return str(dec.Decimal(self.value) / dec.Decimal((1 << Fixed.BITS)))
def __repr__(self):
return str(dec.Decimal(self.value) / dec.Decimal((1 << Fixed.BITS)))
if __name__ == "__main__":
def asserteq(a, b):
if a != b:
raise ValueError(str([a, b]))
asserteq(Fixed.v(-0.75), Fixed.v(-3) / 4)
asserteq(Fixed.v(-1), Fixed.v(-3) // 4)
asserteq(Fixed.v(15.75), Fixed.v(3.5) * 4.5)
asserteq(Fixed.v(1), Fixed.v(-3) % 4)
asserteq(Fixed.v(0), Fixed.v(0.5).floor())
asserteq(Fixed.v(1), Fixed.v(0.5).round())
asserteq(Fixed.v(0), Fixed.v(0.1).round())
asserteq(Fixed.v(1), Fixed.v(0.9).round())
asserteq(Fixed.v(-1), Fixed.v(-0.5).floor())
asserteq(Fixed.v(-1), Fixed.v(-1).floor())
asserteq(Fixed.v(9), Fixed.v(3).pow(2))
asserteq(Fixed.v(27), Fixed.v(3).pow(3))
asserteq(Fixed.v(81), Fixed.v(3).pow(4))
f1 = float(Fixed(1))
print(f"ulp={f1:0.12f}")
import random
rnd = random.Random()
maxerror = 0
for v in range(0, Fixed.PiBits * 4 + 1):
if v % 493 != 0:
continue
fx = Fixed(v)
fxs = float(fx.sqrt())
fps = math.sqrt(float(fx))
if abs(fxs - fps) > 0.1:
print([v, fx, fxs, fps])
maxerror = max(abs(fxs - fps), maxerror)
print(f"sqrt maxerror={maxerror:0.12f}")
maxerror = 0
for i in range(100000):
y = rnd.randint(-(500 << Fixed.BITS), (500 << Fixed.BITS) + 1)
x = rnd.randint(-(100 << Fixed.BITS), (100 << Fixed.BITS) + 1)
fx = Fixed(y)
fx2 = Fixed(x)
if fx == 0 and fx2 < 0:
continue
if fx < 0 and fx2.floor() != fx2:
fx2 = fx2.floor()
fxsv = fx.pow(fx2)
if fxsv.value > (1 << 64):
continue
fxs = float(fxsv)
fps = math.pow(float(fx), float(fx2))
if abs(fxs - fps) > 0.1:
print([fx, fx2, fxs, fps])
maxerror = max(abs(fxs - fps), maxerror)
print(f"pow (max=2^64) maxerror={maxerror:0.12f}")
maxerror = 0
for i in range(1000000):
y = rnd.randint(-(10 << Fixed.BITS), (10 << Fixed.BITS) + 1)
x = rnd.randint(-(10 << Fixed.BITS), (10 << Fixed.BITS) + 1)
fx = Fixed(y)
fx2 = Fixed(x)
fxs = float(fx.atan2(fx2))
fps = math.atan2(float(fx), float(fx2))
if abs(fxs - fps) > 0.1:
print([fx, fx2, fxs, fps])
maxerror = max(abs(fxs - fps), maxerror)
print(f"atan2 maxerror={maxerror:0.12f}")
maxerror = 0
for v in range(-Fixed.PiBits * 2, Fixed.PiBits * 2 + 1):
fx = Fixed(v)
fxsv = fx.tan()
fxs = float(fxsv)
fps = math.tan(float(fx))
if abs(fxs - fps) > 0.1:
print([v, fx, fxs, fps])
maxerror = max(abs(fxs - fps), maxerror)
print(f"tan maxerror={maxerror:0.12f}")
maxerror = 0
for v in range(-Fixed.PiBits * 2, Fixed.PiBits * 2 + 1):
if v % 493 != 0:
continue
fx = Fixed(v)
fxs = float(fx.exp())
fps = math.exp(float(fx))
if abs(fxs - fps) > 0.1:
print([v, fx, fxs, fps])
maxerror = max(abs(fxs - fps), maxerror)
print(f"exp maxerror={maxerror:0.12f}")
maxerror = 0
for v in range(1, Fixed.PiBits * 4 + 1):
if v % 493 != 0:
continue
fx = Fixed(v)
fxs = float(fx.log())
fps = math.log(float(fx))
if abs(fxs - fps) > 0.1:
print([v, fx, fxs, fps])
maxerror = max(abs(fxs - fps), maxerror)
print(f"log maxerror={maxerror:0.12f}")
maxerror = 0
for v in range(-(1 << Fixed.BITS), (1 << Fixed.BITS) + 1):
fx = Fixed(v)
fxsv = fx.asin()
fxs = float(fxsv)
fps = math.asin(float(fx))
if abs(fxs - fps) > 0.1:
print([v, fx, fxs, fps])
maxerror = max(abs(fxs - fps), maxerror)
print(f"asin maxerror={maxerror:0.12f}")
maxerror = 0
for v in range(-(1 << Fixed.BITS), (1 << Fixed.BITS) + 1):
fx = Fixed(v)
fxsv = fx.acos()
fxs = float(fxsv)
fps = math.acos(float(fx))
if abs(fxs - fps) > 0.1:
print([v, fx, fxs, fps])
maxerror = max(abs(fxs - fps), maxerror)
print(f"acos maxerror={maxerror:0.12f}")
maxerror = 0
for v in range(-Fixed.PiBits * 2, Fixed.PiBits * 2 + 1):
fx = Fixed(v)
fxsv = fx.sin()
if fxsv < -1 or fxsv > 1:
raise ValueError
fxs = float(fxsv)
fps = math.sin(float(fx))
if abs(fxs - fps) > 0.1:
print([v, fx, fxs, fps])
maxerror = max(abs(fxs - fps), maxerror)
print(f"sin maxerror={maxerror:0.12f}")
maxerror = 0
for v in range(-Fixed.PiBits * 2, Fixed.PiBits * 2 + 1):
fx = Fixed(v)
fxsv = fx.cos()
if fxsv < -1 or fxsv > 1:
raise ValueError
fxs = float(fxsv)
fps = math.cos(float(fx))
if abs(fxs - fps) > 0.1:
print([v, fx, fxs, fps])
maxerror = max(abs(fxs - fps), maxerror)
print(f"cos maxerror={maxerror:0.12f}")