/
quicktions.pyx
2112 lines (1817 loc) · 73.7 KB
/
quicktions.pyx
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
# cython: language_level=3str
## cython: profile=True
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
# 2011, 2012, 2013, 2014 Python Software Foundation; All Rights Reserved
#
# Based on the "fractions" module in CPython 3.4+.
# https://hg.python.org/cpython/file/b18288f24501/Lib/fractions.py
#
# Updated to match the recent development in CPython.
# https://github.com/python/cpython/blob/main/Lib/fractions.py
#
# Adapted for efficient Cython compilation by Stefan Behnel.
#
"""
Fast fractions data type for rational numbers.
This is an almost-drop-in replacement for the standard library's
"fractions.Fraction".
"""
from __future__ import division, absolute_import, print_function
__all__ = ['Fraction']
__version__ = '1.18'
cimport cython
from cpython.unicode cimport Py_UNICODE_TODECIMAL
from cpython.object cimport Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, Py_GE
from cpython.version cimport PY_MAJOR_VERSION
from cpython.long cimport PyLong_FromString
cdef extern from *:
cdef long LONG_MAX, INT_MAX
cdef long long PY_LLONG_MIN, PY_LLONG_MAX
cdef long long MAX_SMALL_NUMBER "(PY_LLONG_MAX / 100)"
cdef object Rational, Integral, Real, Complex, Decimal, math, operator, re, sys
cdef object PY_MAX_LONG_LONG = PY_LLONG_MAX
from numbers import Rational, Integral, Real, Complex
from decimal import Decimal
import math
import operator
import re
import sys
cdef bint _decimal_supports_integer_ratio = hasattr(Decimal, "as_integer_ratio") # Py3.6+
cdef object _operator_index = operator.index
cdef object math_gcd
try:
math_gcd = math.gcd
except AttributeError:
pass
# Cache widely used 10**x int objects.
DEF CACHED_POW10 = 64 # sys.getsizeof(tuple[58]) == 512 bytes in Py3.7
cdef tuple _cache_pow10():
cdef int i
in_ull = True
l = []
x = 1
for i in range(CACHED_POW10):
l.append(x)
if in_ull:
try:
_C_POW_10[i] = x
except OverflowError:
in_ull = False
x *= 10
return tuple(l)
cdef unsigned long long[CACHED_POW10] _C_POW_10
cdef tuple POW_10 = _cache_pow10()
cdef unsigned long long _c_pow10(Py_ssize_t i):
return _C_POW_10[i]
cdef pow10(long long i):
if 0 <= i < CACHED_POW10:
return POW_10[i]
else:
return 10 ** (<object> i)
# Half-private GCD implementation.
cdef extern from *:
"""
#if PY_VERSION_HEX >= 0x030c00a5 && defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue)
#define __Quicktions_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) (x))
#if CYTHON_COMPILING_IN_CPYTHON
#define __Quicktions_PyLong_CompactValueUnsigned(x) ((unsigned long long) (((PyLongObject*)x)->long_value.ob_digit[0]))
#else
#define __Quicktions_PyLong_CompactValueUnsigned(x) ((unsigned long long) PyUnstable_Long_CompactValue((PyLongObject*) (x))))
#endif
#elif PY_VERSION_HEX < 0x030c0000 && CYTHON_COMPILING_IN_CPYTHON
#define __Quicktions_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1)
#define __Quicktions_PyLong_CompactValueUnsigned(x) ((unsigned long long) ((Py_SIZE(x) == 0) ? 0 : (((PyLongObject*)x)->ob_digit)[0]))
#else
#define __Quicktions_PyLong_IsCompact(x) (0)
#define __Quicktions_PyLong_CompactValueUnsigned(x) (0U)
#endif
#if PY_VERSION_HEX < 0x030500F0 || PY_VERSION_HEX >= 0x030d0000 || !CYTHON_COMPILING_IN_CPYTHON
#define _PyLong_GCD(a, b) (NULL)
#endif
#ifdef __GCC__
#define __Quicktions_IS_GCC 1
#define __Quicktions_trailing_zeros_uint(x) __builtin_ctz(x)
#define __Quicktions_trailing_zeros_ulong(x) __builtin_ctzl(x)
#define __Quicktions_trailing_zeros_ullong(x) __builtin_ctzll(x)
#else
#define __Quicktions_IS_GCC 0
#define __Quicktions_trailing_zeros_uint(x) (0)
#define __Quicktions_trailing_zeros_ulong(x) (0)
#define __Quicktions_trailing_zeros_ullong(x) (0)
#endif
"""
bint PyLong_IsCompact "__Quicktions_PyLong_IsCompact" (x)
Py_ssize_t PyLong_CompactValueUnsigned "__Quicktions_PyLong_CompactValueUnsigned" (x)
# CPython 3.5-3.12 has a fast PyLong GCD implementation that we can use.
# In CPython 3.13, math.gcd() is fast enough to call it directly.
int PY_VERSION_HEX
int HAS_PYLONG_GCD "(CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000)"
_PyLong_GCD(a, b)
bint IS_GCC "__Quicktions_IS_GCC"
int trailing_zeros_uint "__Quicktions_trailing_zeros_uint" (unsigned int x)
int trailing_zeros_ulong "__Quicktions_trailing_zeros_ulong" (unsigned long x)
int trailing_zeros_ullong "__Quicktions_trailing_zeros_ullong" (unsigned long long x)
cpdef _gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b as a non-negative number.
"""
if PyLong_IsCompact(a) and PyLong_IsCompact(b):
return _c_gcd(PyLong_CompactValueUnsigned(a), PyLong_CompactValueUnsigned(b))
if PY_VERSION_HEX >= 0x030d0000:
return math_gcd(a, b)
if PY_VERSION_HEX < 0x030500F0 or not HAS_PYLONG_GCD:
return _gcd_fallback(a, b)
return _PyLong_GCD(a, b)
ctypedef unsigned long long ullong
ctypedef unsigned long ulong
ctypedef unsigned int uint
ctypedef fused cunumber:
ullong
ulong
uint
cdef ullong _abs(long long x):
if x == PY_LLONG_MIN:
return (<ullong>PY_LLONG_MAX) + 1
return abs(x)
cdef cunumber _igcd(cunumber a, cunumber b):
"""Euclid's GCD algorithm"""
if IS_GCC:
return _binary_gcd(a, b)
else:
return _euclid_gcd(a, b)
cdef cunumber _euclid_gcd(cunumber a, cunumber b):
"""Euclid's GCD algorithm"""
while b:
a, b = b, a%b
return a
cdef inline int trailing_zeros(cunumber x):
if cunumber is uint:
return trailing_zeros_uint(x)
elif cunumber is ulong:
return trailing_zeros_ulong(x)
else:
return trailing_zeros_ullong(x)
cdef cunumber _binary_gcd(cunumber a, cunumber b):
# See https://en.wikipedia.org/wiki/Binary_GCD_algorithm
if not a:
return b
if not b:
return a
cdef int i = trailing_zeros(a)
a >>= i
cdef int j = trailing_zeros(b)
b >>= j
cdef int k = min(i, j)
while True:
if a > b:
a, b = b, a
b -= a
if not b:
return a << k
b >>= trailing_zeros(b)
cdef _py_gcd(ullong a, ullong b):
if a <= <ullong>INT_MAX and b <= <ullong>INT_MAX:
return <int> _igcd[uint](<uint> a, <uint> b)
elif a <= <ullong>LONG_MAX and b <= <ullong>LONG_MAX:
return <long> _igcd[ulong](<ulong> a, <ulong> b)
elif b:
a = _igcd[ullong](a, b)
# try PyInt downcast in Py2
if PY_MAJOR_VERSION < 3 and a <= <ullong>LONG_MAX:
return <long>a
return a
cdef ullong _c_gcd(ullong a, ullong b):
if a <= <ullong>INT_MAX and b <= <ullong>INT_MAX:
return _igcd[uint](<uint> a, <uint> b)
elif a <= <ullong>LONG_MAX and b <= <ullong>LONG_MAX:
return _igcd[ulong](<ulong> a, <ulong> b)
else:
return _igcd[ullong](a, b)
cdef _gcd_fallback(a, b):
"""Fallback GCD implementation if _PyLong_GCD() is not available.
"""
# Try doing the computation in C space. If the numbers are too
# large at the beginning, do object calculations until they are small enough.
cdef ullong au, bu
cdef long long ai, bi
# Optimistically try to switch to C space.
try:
ai, bi = a, b
except OverflowError:
pass
else:
au = _abs(ai)
bu = _abs(bi)
return _py_gcd(au, bu)
# Do object calculation until we reach the C space limit.
a = abs(a)
b = abs(b)
while b > PY_MAX_LONG_LONG:
a, b = b, a%b
while b and a > PY_MAX_LONG_LONG:
a, b = b, a%b
if not b:
return a
return _py_gcd(a, b)
# Constants related to the hash implementation; hash(x) is based
# on the reduction of x modulo the prime _PyHASH_MODULUS.
cdef Py_hash_t _PyHASH_MODULUS
try:
_PyHASH_MODULUS = sys.hash_info.modulus
except AttributeError: # pre Py3.2
# adapted from pyhash.h in Py3.4
_PyHASH_MODULUS = (<Py_hash_t>1) << (61 if sizeof(Py_hash_t) >= 8 else 31) - 1
# Value to be used for rationals that reduce to infinity modulo
# _PyHASH_MODULUS.
cdef Py_hash_t _PyHASH_INF
try:
_PyHASH_INF = sys.hash_info.inf
except AttributeError: # pre Py3.2
_PyHASH_INF = hash(float('+inf'))
# Helpers for formatting
cdef _round_to_exponent(n, d, exponent, bint no_neg_zero=False):
"""Round a rational number to the nearest multiple of a given power of 10.
Rounds the rational number n/d to the nearest integer multiple of
10**exponent, rounding to the nearest even integer multiple in the case of
a tie. Returns a pair (sign: bool, significand: int) representing the
rounded value (-1)**sign * significand * 10**exponent.
If no_neg_zero is true, then the returned sign will always be False when
the significand is zero. Otherwise, the sign reflects the sign of the
input.
d must be positive, but n and d need not be relatively prime.
"""
if exponent >= 0:
d *= 10**exponent
else:
n *= 10**-exponent
# The divmod quotient is correct for round-ties-towards-positive-infinity;
# In the case of a tie, we zero out the least significant bit of q.
q, r = divmod(n + (d >> 1), d)
if r == 0 and d & 1 == 0:
q &= -2
cdef bint sign = q < 0 if no_neg_zero else n < 0
return sign, abs(q)
cdef _round_to_figures(n, d, Py_ssize_t figures):
"""Round a rational number to a given number of significant figures.
Rounds the rational number n/d to the given number of significant figures
using the round-ties-to-even rule, and returns a triple
(sign: bool, significand: int, exponent: int) representing the rounded
value (-1)**sign * significand * 10**exponent.
In the special case where n = 0, returns a significand of zero and
an exponent of 1 - figures, for compatibility with formatting.
Otherwise, the returned significand satisfies
10**(figures - 1) <= significand < 10**figures.
d must be positive, but n and d need not be relatively prime.
figures must be positive.
"""
# Special case for n == 0.
if n == 0:
return False, 0, 1 - figures
cdef bint sign
# Find integer m satisfying 10**(m - 1) <= abs(n)/d <= 10**m. (If abs(n)/d
# is a power of 10, either of the two possible values for m is fine.)
str_n, str_d = str(abs(n)), str(d)
cdef Py_ssize_t m = len(str_n) - len(str_d) + (str_d <= str_n)
# Round to a multiple of 10**(m - figures). The significand we get
# satisfies 10**(figures - 1) <= significand <= 10**figures.
exponent = m - figures
sign, significand = _round_to_exponent(n, d, exponent)
# Adjust in the case where significand == 10**figures, to ensure that
# 10**(figures - 1) <= significand < 10**figures.
if len(str(significand)) == figures + 1:
significand //= 10
exponent += 1
return sign, significand, exponent
# Pattern for matching non-float-style format specifications.
cdef object _GENERAL_FORMAT_SPECIFICATION_MATCHER = re.compile(r"""
(?:
(?P<fill>.)?
(?P<align>[<>=^])
)?
(?P<sign>[-+ ]?)
# Alt flag forces a slash and denominator in the output, even for
# integer-valued Fraction objects.
(?P<alt>\#)?
# We don't implement the zeropad flag since there's no single obvious way
# to interpret it.
(?P<minimumwidth>0|[1-9][0-9]*)?
(?P<thousands_sep>[,_])?
$
""", re.DOTALL | re.VERBOSE).match
# Pattern for matching float-style format specifications;
# supports 'e', 'E', 'f', 'F', 'g', 'G' and '%' presentation types.
cdef object _FLOAT_FORMAT_SPECIFICATION_MATCHER = re.compile(r"""
(?:
(?P<fill>.)?
(?P<align>[<>=^])
)?
(?P<sign>[-+ ]?)
(?P<no_neg_zero>z)?
(?P<alt>\#)?
# A '0' that's *not* followed by another digit is parsed as a minimum width
# rather than a zeropad flag.
(?P<zeropad>0(?=[0-9]))?
(?P<minimumwidth>0|[1-9][0-9]*)?
(?P<thousands_sep>[,_])?
(?:\.(?P<precision>0|[1-9][0-9]*))?
(?P<presentation_type>[eEfFgG%])
$
""", re.DOTALL | re.VERBOSE).match
cdef object NOINIT = object()
cdef class Fraction:
"""A Rational number.
Takes a string like '3/2' or '1.5', another Rational instance, a
numerator/denominator pair, or a float.
Examples
--------
>>> Fraction(10, -8)
Fraction(-5, 4)
>>> Fraction(Fraction(1, 7), 5)
Fraction(1, 35)
>>> Fraction(Fraction(1, 7), Fraction(2, 3))
Fraction(3, 14)
>>> Fraction('314')
Fraction(314, 1)
>>> Fraction('-35/4')
Fraction(-35, 4)
>>> Fraction('3.1415') # conversion from numeric string
Fraction(6283, 2000)
>>> Fraction('-47e-2') # string may include a decimal exponent
Fraction(-47, 100)
>>> Fraction(1.47) # direct construction from float (exact conversion)
Fraction(6620291452234629, 4503599627370496)
>>> Fraction(2.25)
Fraction(9, 4)
>>> from decimal import Decimal
>>> Fraction(Decimal('1.47'))
Fraction(147, 100)
"""
cdef _numerator
cdef _denominator
cdef Py_hash_t _hash
def __cinit__(self, numerator=0, denominator=None):
self._hash = -1
if numerator is NOINIT:
return # fast-path for external initialisation
cdef bint _normalize = True
if denominator is None:
if type(numerator) is int or type(numerator) is long:
self._numerator = numerator
self._denominator = 1
return
elif type(numerator) is float:
# Exact conversion
self._numerator, self._denominator = numerator.as_integer_ratio()
return
elif type(numerator) is Fraction:
self._numerator = (<Fraction>numerator)._numerator
self._denominator = (<Fraction>numerator)._denominator
return
elif isinstance(numerator, unicode):
numerator, denominator, is_normalised = _parse_fraction(
<unicode>numerator, len(<unicode>numerator))
if is_normalised:
_normalize = False
# fall through to normalisation below
elif PY_MAJOR_VERSION < 3 and isinstance(numerator, bytes):
numerator, denominator, is_normalised = _parse_fraction(
<bytes>numerator, len(<bytes>numerator))
if is_normalised:
_normalize = False
# fall through to normalisation below
elif isinstance(numerator, float):
# Exact conversion
self._numerator, self._denominator = numerator.as_integer_ratio()
return
elif isinstance(numerator, (Fraction, Rational)):
self._numerator = numerator.numerator
self._denominator = numerator.denominator
return
elif isinstance(numerator, Decimal):
if _decimal_supports_integer_ratio:
# Exact conversion
self._numerator, self._denominator = numerator.as_integer_ratio()
else:
value = Fraction.from_decimal(numerator)
self._numerator = (<Fraction>value)._numerator
self._denominator = (<Fraction>value)._denominator
return
else:
raise TypeError("argument should be a string "
"or a Rational instance")
elif type(numerator) is int is type(denominator):
pass # *very* normal case
elif PY_MAJOR_VERSION < 3 and type(numerator) is long is type(denominator):
pass # *very* normal case
elif type(numerator) is Fraction is type(denominator):
numerator, denominator = (
(<Fraction>numerator)._numerator * (<Fraction>denominator)._denominator,
(<Fraction>denominator)._numerator * (<Fraction>numerator)._denominator
)
elif (isinstance(numerator, (Fraction, Rational)) and
isinstance(denominator, (Fraction, Rational))):
numerator, denominator = (
numerator.numerator * denominator.denominator,
denominator.numerator * numerator.denominator
)
else:
raise TypeError("both arguments should be "
"Rational instances")
if denominator == 0:
raise ZeroDivisionError(f'Fraction({numerator}, 0)')
if _normalize:
if not isinstance(numerator, int):
numerator = int(numerator)
if not isinstance(denominator, int):
denominator = int(denominator)
g = _gcd(numerator, denominator)
# NOTE: 'is' tests on integers are generally a bad idea, but
# they are fast and if they fail here, it'll still be correct
if denominator < 0:
if g is 1:
numerator = -numerator
denominator = -denominator
else:
g = -g
if g is not 1:
numerator //= g
denominator //= g
self._numerator = numerator
self._denominator = denominator
@classmethod
def from_float(cls, f):
"""Converts a finite float to a rational number, exactly.
Beware that Fraction.from_float(0.3) != Fraction(3, 10).
"""
try:
ratio = f.as_integer_ratio()
except (ValueError, OverflowError, AttributeError):
pass # not something we can convert, raise concrete exceptions below
else:
return cls(*ratio)
if isinstance(f, Integral):
return cls(f)
elif not isinstance(f, float):
raise TypeError(f"{cls.__name__}.from_float() only takes floats, not {f!r} ({type(f).__name__})")
if math.isinf(f):
raise OverflowError(f"Cannot convert {f!r} to {cls.__name__}.")
raise ValueError(f"Cannot convert {f!r} to {cls.__name__}.")
@classmethod
def from_decimal(cls, dec):
"""Converts a finite Decimal instance to a rational number, exactly."""
cdef Py_ssize_t exp
if isinstance(dec, Integral):
dec = Decimal(int(dec))
elif not isinstance(dec, Decimal):
raise TypeError(
f"{cls.__name__}.from_decimal() only takes Decimals, not {dec!r} ({type(dec).__name__})")
if dec.is_infinite():
raise OverflowError(f"Cannot convert {dec} to {cls.__name__}.")
if dec.is_nan():
raise ValueError(f"Cannot convert {dec} to {cls.__name__}.")
if _decimal_supports_integer_ratio:
num, denom = dec.as_integer_ratio()
return _fraction_from_coprime_ints(num, denom, cls)
sign, digits, exp = dec.as_tuple()
digits = int(''.join(map(str, digits)))
if sign:
digits = -digits
if exp >= 0:
return _fraction_from_coprime_ints(digits * pow10(exp), 1, cls)
else:
return cls(digits, pow10(-exp))
def is_integer(self):
"""Return True if the Fraction is an integer."""
return self._denominator == 1
def as_integer_ratio(self):
"""Return a pair of integers, whose ratio is equal to the original Fraction.
The ratio is in lowest terms and has a positive denominator.
"""
return (self._numerator, self._denominator)
def limit_denominator(self, max_denominator=1000000):
"""Closest Fraction to self with denominator at most max_denominator.
>>> Fraction('3.141592653589793').limit_denominator(10)
Fraction(22, 7)
>>> Fraction('3.141592653589793').limit_denominator(100)
Fraction(311, 99)
>>> Fraction(4321, 8765).limit_denominator(10000)
Fraction(4321, 8765)
"""
# Algorithm notes: For any real number x, define a *best upper
# approximation* to x to be a rational number p/q such that:
#
# (1) p/q >= x, and
# (2) if p/q > r/s >= x then s > q, for any rational r/s.
#
# Define *best lower approximation* similarly. Then it can be
# proved that a rational number is a best upper or lower
# approximation to x if, and only if, it is a convergent or
# semiconvergent of the (unique shortest) continued fraction
# associated to x.
#
# To find a best rational approximation with denominator <= M,
# we find the best upper and lower approximations with
# denominator <= M and take whichever of these is closer to x.
# In the event of a tie, the bound with smaller denominator is
# chosen. If both denominators are equal (which can happen
# only when max_denominator == 1 and self is midway between
# two integers) the lower bound---i.e., the floor of self, is
# taken.
if max_denominator < 1:
raise ValueError("max_denominator should be at least 1")
if self._denominator <= max_denominator:
return Fraction(self)
p0, q0, p1, q1 = 0, 1, 1, 0
n, d = self._numerator, self._denominator
while True:
a = n//d
q2 = q0+a*q1
if q2 > max_denominator:
break
p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
n, d = d, n-a*d
k = (max_denominator-q0)//q1
# Determine which of the candidates (p0+k*p1)/(q0+k*q1) and p1/q1 is
# closer to self. The distance between them is 1/(q1*(q0+k*q1)), while
# the distance from p1/q1 to self is d/(q1*self._denominator). So we
# need to compare 2*(q0+k*q1) with self._denominator/d.
if 2*d*(q0+k*q1) <= self._denominator:
return _fraction_from_coprime_ints(p1, q1)
else:
return _fraction_from_coprime_ints(p0+k*p1, q0+k*q1)
@property
def numerator(self):
return self._numerator
@property
def denominator(self):
return self._denominator
def __repr__(self):
"""repr(self)"""
return '%s(%s, %s)' % (self.__class__.__name__,
self._numerator, self._denominator)
def __str__(self):
"""str(self)"""
if self._denominator == 1:
return str(self._numerator)
elif PY_MAJOR_VERSION > 2:
return f'{self._numerator}/{self._denominator}'
else:
return '%s/%s' % (self._numerator, self._denominator)
@cython.final
cdef _format_general(self, dict match):
"""Helper method for __format__.
Handles fill, alignment, signs, and thousands separators in the
case of no presentation type.
"""
# Validate and parse the format specifier.
fill = match["fill"] or " "
cdef Py_UCS4 align = ord(match["align"] or ">")
pos_sign = "" if match["sign"] == "-" else match["sign"]
cdef bint alternate_form = match["alt"]
cdef Py_ssize_t minimumwidth = int(match["minimumwidth"] or "0")
thousands_sep = match["thousands_sep"] or ''
if PY_VERSION_HEX < 0x03060000:
legacy_thousands_sep, thousands_sep = thousands_sep, ''
cdef Py_ssize_t first_pos # Py2/3.5-only
# Determine the body and sign representation.
n, d = self._numerator, self._denominator
if PY_VERSION_HEX < 0x03060000 and legacy_thousands_sep:
# Insert thousands separators if required.
body = str(abs(n))
first_pos = 1 + (len(body) - 1) % 3
body = body[:first_pos] + "".join([
legacy_thousands_sep + body[pos : pos + 3]
for pos in range(first_pos, len(body), 3)
])
if d > 1 or alternate_form:
den = str(abs(d))
first_pos = 1 + (len(den) - 1) % 3
den = den[:first_pos] + "".join([
legacy_thousands_sep + den[pos: pos + 3]
for pos in range(first_pos, len(den), 3)
])
body += "/" + den
elif d > 1 or alternate_form:
body = f"{abs(n):{thousands_sep}}/{d:{thousands_sep}}"
else:
body = f"{abs(n):{thousands_sep}}"
sign = '-' if n < 0 else pos_sign
# Pad with fill character if necessary and return.
padding = fill * (minimumwidth - len(sign) - len(body))
if align == u">":
return padding + sign + body
elif align == u"<":
return sign + body + padding
elif align == u"^":
half = len(padding) // 2
return padding[:half] + sign + body + padding[half:]
else: # align == u"="
return sign + padding + body
@cython.final
cdef _format_float_style(self, dict match):
"""Helper method for __format__; handles float presentation types."""
fill = match["fill"] or " "
align = match["align"] or ">"
pos_sign = "" if match["sign"] == "-" else match["sign"]
cdef bint no_neg_zero = match["no_neg_zero"]
cdef bint alternate_form = match["alt"]
cdef bint zeropad = match["zeropad"]
cdef Py_ssize_t minimumwidth = int(match["minimumwidth"] or "0")
thousands_sep = match["thousands_sep"]
cdef Py_ssize_t precision = int(match["precision"] or "6")
cdef Py_UCS4 presentation_type = ord(match["presentation_type"])
cdef bint trim_zeros = presentation_type in u"gG" and not alternate_form
cdef bint trim_point = not alternate_form
exponent_indicator = "E" if presentation_type in u"EFG" else "e"
cdef bint negative, scientific
cdef Py_ssize_t exponent, figures
# Round to get the digits we need, figure out where to place the point,
# and decide whether to use scientific notation. 'point_pos' is the
# relative to the _end_ of the digit string: that is, it's the number
# of digits that should follow the point.
if presentation_type in u"fF%":
exponent = -precision
if presentation_type == u"%":
exponent -= 2
negative, significand = _round_to_exponent(
self._numerator, self._denominator, exponent, no_neg_zero)
scientific = False
point_pos = precision
else: # presentation_type in "eEgG"
figures = (
max(precision, 1)
if presentation_type in u"gG"
else precision + 1
)
negative, significand, exponent = _round_to_figures(
self._numerator, self._denominator, figures)
scientific = (
presentation_type in u"eE"
or exponent > 0
or exponent + figures <= -4
)
point_pos = figures - 1 if scientific else -exponent
# Get the suffix - the part following the digits, if any.
if presentation_type == u"%":
suffix = "%"
elif scientific:
#suffix = f"{exponent_indicator}{exponent + point_pos:+03d}"
suffix = "%s%+03d" % (exponent_indicator, exponent + point_pos)
else:
suffix = ""
# String of output digits, padded sufficiently with zeros on the left
# so that we'll have at least one digit before the decimal point.
digits = f"{significand:0{point_pos + 1}d}"
# Before padding, the output has the form f"{sign}{leading}{trailing}",
# where `leading` includes thousands separators if necessary and
# `trailing` includes the decimal separator where appropriate.
sign = "-" if negative else pos_sign
leading = digits[: len(digits) - point_pos]
frac_part = digits[len(digits) - point_pos :]
if trim_zeros:
frac_part = frac_part.rstrip("0")
separator = "" if trim_point and not frac_part else "."
trailing = separator + frac_part + suffix
# Do zero padding if required.
if zeropad:
min_leading = minimumwidth - len(sign) - len(trailing)
# When adding thousands separators, they'll be added to the
# zero-padded portion too, so we need to compensate.
leading = leading.zfill(
3 * min_leading // 4 + 1 if thousands_sep else min_leading
)
# Insert thousands separators if required.
if thousands_sep:
first_pos = 1 + (len(leading) - 1) % 3
leading = leading[:first_pos] + "".join([
thousands_sep + leading[pos : pos + 3]
for pos in range(first_pos, len(leading), 3)
])
# We now have a sign and a body. Pad with fill character if necessary
# and return.
body = leading + trailing
padding = fill * (minimumwidth - len(sign) - len(body))
if align == ">":
return padding + sign + body
elif align == "<":
return sign + body + padding
elif align == "^":
half = len(padding) // 2
return padding[:half] + sign + body + padding[half:]
else: # align == "="
return sign + padding + body
def __format__(self, format_spec, /):
"""Format this fraction according to the given format specification."""
if match := _GENERAL_FORMAT_SPECIFICATION_MATCHER(format_spec):
return self._format_general(match.groupdict())
if match := _FLOAT_FORMAT_SPECIFICATION_MATCHER(format_spec):
# Refuse the temptation to guess if both alignment _and_
# zero padding are specified.
match_groups = match.groupdict()
if match_groups["align"] is None or match_groups["zeropad"] is None:
return self._format_float_style(match_groups)
raise ValueError(
f"Invalid format specifier {format_spec!r} "
f"for object of type {type(self).__name__!r}"
)
def __add__(a, b):
"""a + b"""
return forward(a, b, _add, _math_op_add)
def __radd__(b, a):
"""a + b"""
return reverse(a, b, _add, _math_op_add)
def __sub__(a, b):
"""a - b"""
return forward(a, b, _sub, _math_op_sub)
def __rsub__(b, a):
"""a - b"""
return reverse(a, b, _sub, _math_op_sub)
def __mul__(a, b):
"""a * b"""
return forward(a, b, _mul, _math_op_mul)
def __rmul__(b, a):
"""a * b"""
return reverse(a, b, _mul, _math_op_mul)
def __div__(a, b):
"""a / b"""
return forward(a, b, _div, _math_op_div)
def __rdiv__(b, a):
"""a / b"""
return reverse(a, b, _div, _math_op_div)
def __truediv__(a, b):
"""a / b"""
return forward(a, b, _div, _math_op_truediv)
def __rtruediv__(b, a):
"""a / b"""
return reverse(a, b, _div, _math_op_truediv)
def __floordiv__(a, b):
"""a // b"""
return forward(a, b, _floordiv, _math_op_floordiv)
def __rfloordiv__(b, a):
"""a // b"""
return reverse(a, b, _floordiv, _math_op_floordiv)
def __mod__(a, b):
"""a % b"""
return forward(a, b, _mod, _math_op_mod)
def __rmod__(b, a):
"""a % b"""
return reverse(a, b, _mod, _math_op_mod)
def __divmod__(a, b):
"""divmod(self, other): The pair (self // other, self % other).
Sometimes this can be computed faster than the pair of
operations.
"""
return forward(a, b, _divmod, _math_op_divmod)
def __rdivmod__(b, a):
"""divmod(self, other): The pair (self // other, self % other).
Sometimes this can be computed faster than the pair of
operations.
"""
return reverse(a, b, _divmod, _math_op_divmod)
def __pow__(a, b, x):
"""a ** b
If b is not an integer, the result will be a float or complex
since roots are generally irrational. If b is an integer, the
result will be rational.
"""
if x is not None:
return NotImplemented
if isinstance(b, (int, long)):
return _pow(a.numerator, a.denominator, b, 1)
elif isinstance(b, (Fraction, Rational)):
return _pow(a.numerator, a.denominator, b.numerator, b.denominator)
else:
return (a.numerator / a.denominator) ** b
def __rpow__(b, a, x):
"""a ** b
If b is not an integer, the result will be a float or complex
since roots are generally irrational. If b is an integer, the
result will be rational.
"""
if x is not None:
return NotImplemented
bn, bd = b.numerator, b.denominator
if bd == 1 and bn >= 0:
# If a is an int, keep it that way if possible.
return a ** bn
if isinstance(a, (int, long)):
return _pow(a, 1, bn, bd)
if isinstance(a, (Fraction, Rational)):
return _pow(a.numerator, a.denominator, bn, bd)
if bd == 1:
return a ** bn
return a ** (bn / bd)
def __pos__(a):
"""+a: Coerces a subclass instance to Fraction"""
if type(a) is Fraction:
return a
return _fraction_from_coprime_ints(a._numerator, a._denominator)
def __neg__(a):
"""-a"""
return _fraction_from_coprime_ints(-a._numerator, a._denominator)
def __abs__(a):
"""abs(a)"""
return _fraction_from_coprime_ints(abs(a._numerator), a._denominator)
def __int__(a):
"""int(a)"""
if a._numerator < 0:
return _operator_index(-(-a._numerator // a._denominator))
else:
return _operator_index(a._numerator // a._denominator)
def __trunc__(a):
"""math.trunc(a)"""
if a._numerator < 0:
return -(-a._numerator // a._denominator)
else:
return a._numerator // a._denominator
def __floor__(a):