annotate Lib/fractions.py @ 54294:dba767bc3155 legacy-trunk

remove mention of old ctypes version
author Benjamin Peterson <benjamin@python.org>
date Sat, 23 May 2009 20:59:09 +0000
parents 114059c26794
children 9dc5aa62be72
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
1 # Originally contributed by Sjoerd Mullender.
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
2 # Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>.
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
3
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
4 """Rational, infinite-precision, real numbers."""
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
5
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
6 from __future__ import division
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
7 import math
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
8 import numbers
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
9 import operator
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
10 import re
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
11
46727
0e76a8f34769 The __all__ variable forgot to expose the gcd() function.
Raymond Hettinger <python@rcn.com>
parents: 45332
diff changeset
12 __all__ = ['Fraction', 'gcd']
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
13
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
14 Rational = numbers.Rational
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
15
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
16
44993
4dd0fcf3daf7 Make rational.gcd() public and allow Rational to take decimal strings, per
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44937
diff changeset
17 def gcd(a, b):
4dd0fcf3daf7 Make rational.gcd() public and allow Rational to take decimal strings, per
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44937
diff changeset
18 """Calculate the Greatest Common Divisor of a and b.
945
465b9841770e Initial revision
Guido van Rossum <guido@python.org>
parents:
diff changeset
19
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
20 Unless b==0, the result will have the same sign as b (so that when
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
21 b is divided by it, the result comes out positive).
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
22 """
28788
558689b6d7f0 Run these demo scripts through reindent.py to give them 4-space indents. I've verified that their output is unchanged.
Andrew M. Kuchling <amk@amk.ca>
parents: 28787
diff changeset
23 while b:
558689b6d7f0 Run these demo scripts through reindent.py to give them 4-space indents. I've verified that their output is unchanged.
Andrew M. Kuchling <amk@amk.ca>
parents: 28787
diff changeset
24 a, b = b, a%b
558689b6d7f0 Run these demo scripts through reindent.py to give them 4-space indents. I've verified that their output is unchanged.
Andrew M. Kuchling <amk@amk.ca>
parents: 28787
diff changeset
25 return a
945
465b9841770e Initial revision
Guido van Rossum <guido@python.org>
parents:
diff changeset
26
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
27
45113
04653f92664f Make the Rational constructor accept '3.' and '.2' as well as '3.2'.
Mark Dickinson <dickinsm@gmail.com>
parents: 45080
diff changeset
28 _RATIONAL_FORMAT = re.compile(r"""
04653f92664f Make the Rational constructor accept '3.' and '.2' as well as '3.2'.
Mark Dickinson <dickinsm@gmail.com>
parents: 45080
diff changeset
29 \A\s* # optional whitespace at the start, then
04653f92664f Make the Rational constructor accept '3.' and '.2' as well as '3.2'.
Mark Dickinson <dickinsm@gmail.com>
parents: 45080
diff changeset
30 (?P<sign>[-+]?) # an optional sign, then
04653f92664f Make the Rational constructor accept '3.' and '.2' as well as '3.2'.
Mark Dickinson <dickinsm@gmail.com>
parents: 45080
diff changeset
31 (?=\d|\.\d) # lookahead for digit or .digit
04653f92664f Make the Rational constructor accept '3.' and '.2' as well as '3.2'.
Mark Dickinson <dickinsm@gmail.com>
parents: 45080
diff changeset
32 (?P<num>\d*) # numerator (possibly empty)
53324
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
33 (?: # followed by
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
34 (?:/(?P<denom>\d+))? # an optional denominator
45113
04653f92664f Make the Rational constructor accept '3.' and '.2' as well as '3.2'.
Mark Dickinson <dickinsm@gmail.com>
parents: 45080
diff changeset
35 | # or
53324
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
36 (?:\.(?P<decimal>\d*))? # an optional fractional part
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
37 (?:E(?P<exp>[-+]?\d+))? # and optional exponent
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
38 )
45113
04653f92664f Make the Rational constructor accept '3.' and '.2' as well as '3.2'.
Mark Dickinson <dickinsm@gmail.com>
parents: 45080
diff changeset
39 \s*\Z # and optional whitespace to finish
53324
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
40 """, re.VERBOSE | re.IGNORECASE)
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
41
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
42
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
43 class Fraction(Rational):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
44 """This class implements rational numbers.
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
45
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
46 Fraction(8, 6) will produce a rational number equivalent to
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
47 4/3. Both arguments must be Integral. The numerator defaults to 0
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
48 and the denominator defaults to 1 so that Fraction(3) == 3 and
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
49 Fraction() == 0.
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
50
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
51 Fractions can also be constructed from strings of the form
44993
4dd0fcf3daf7 Make rational.gcd() public and allow Rational to take decimal strings, per
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44937
diff changeset
52 '[-+]?[0-9]+((/|.)[0-9]+)?', optionally surrounded by spaces.
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
53
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
54 """
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
55
45080
678509f9a03f Roll back r60248. It's useful to encourage users not to change Rational
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45075
diff changeset
56 __slots__ = ('_numerator', '_denominator')
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
57
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
58 # We're immutable, so use __new__ not __init__
53346
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
59 def __new__(cls, numerator=0, denominator=None):
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
60 """Constructs a Fraction.
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
61
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
62 Takes a string like '3/2' or '1.5', another Fraction, or a
44993
4dd0fcf3daf7 Make rational.gcd() public and allow Rational to take decimal strings, per
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44937
diff changeset
63 numerator/denominator pair.
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
64
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
65 """
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
66 self = super(Fraction, cls).__new__(cls)
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
67
53346
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
68 if denominator is None:
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
69 if isinstance(numerator, Rational):
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
70 self._numerator = numerator.numerator
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
71 self._denominator = numerator.denominator
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
72 return self
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
73
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
74 elif isinstance(numerator, basestring):
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
75 # Handle construction from strings.
53324
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
76 m = _RATIONAL_FORMAT.match(numerator)
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
77 if m is None:
53324
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
78 raise ValueError('Invalid literal for Fraction: %r' %
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
79 numerator)
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
80 numerator = int(m.group('num') or '0')
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
81 denom = m.group('denom')
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
82 if denom:
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
83 denominator = int(denom)
44993
4dd0fcf3daf7 Make rational.gcd() public and allow Rational to take decimal strings, per
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44937
diff changeset
84 else:
53324
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
85 denominator = 1
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
86 decimal = m.group('decimal')
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
87 if decimal:
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
88 scale = 10**len(decimal)
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
89 numerator = numerator * scale + int(decimal)
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
90 denominator *= scale
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
91 exp = m.group('exp')
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
92 if exp:
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
93 exp = int(exp)
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
94 if exp >= 0:
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
95 numerator *= 10**exp
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
96 else:
85597e55668c Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Mark Dickinson <dickinsm@gmail.com>
parents: 50526
diff changeset
97 denominator *= 10**-exp
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
98 if m.group('sign') == '-':
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
99 numerator = -numerator
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
100
53346
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
101 else:
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
102 raise TypeError("argument should be a string "
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
103 "or a Rational instance")
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
104
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
105 elif (isinstance(numerator, Rational) and
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
106 isinstance(denominator, Rational)):
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
107 numerator, denominator = (
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
108 numerator.numerator * denominator.denominator,
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
109 denominator.numerator * numerator.denominator
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
110 )
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
111 else:
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
112 raise TypeError("both arguments should be "
114059c26794 Issue #5812: The two-argument form of the Fraction constructor
Mark Dickinson <dickinsm@gmail.com>
parents: 53324
diff changeset
113 "Rational instances")
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
114
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
115 if denominator == 0:
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
116 raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
44993
4dd0fcf3daf7 Make rational.gcd() public and allow Rational to take decimal strings, per
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44937
diff changeset
117 g = gcd(numerator, denominator)
45331
c7e683d52b3b Performance optimizations on Fraction's constructor.
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45305
diff changeset
118 self._numerator = numerator // g
c7e683d52b3b Performance optimizations on Fraction's constructor.
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45305
diff changeset
119 self._denominator = denominator // g
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
120 return self
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
121
45305
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
122 @classmethod
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
123 def from_float(cls, f):
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
124 """Converts a finite float to a rational number, exactly.
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
125
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
126 Beware that Fraction.from_float(0.3) != Fraction(3, 10).
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
127
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
128 """
47920
bd435e8b2e28 Issue 3285: Fractions from_float() and from_decimal() accept Integral arguments.
Raymond Hettinger <python@rcn.com>
parents: 47917
diff changeset
129 if isinstance(f, numbers.Integral):
50526
6df3d08b89e4 Manually merge r68095,68186,68187,68188,68190 from 2.6 branch.
Georg Brandl <georg@python.org>
parents: 47920
diff changeset
130 return cls(f)
47920
bd435e8b2e28 Issue 3285: Fractions from_float() and from_decimal() accept Integral arguments.
Raymond Hettinger <python@rcn.com>
parents: 47917
diff changeset
131 elif not isinstance(f, float):
45305
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
132 raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
133 (cls.__name__, f, type(f).__name__))
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
134 if math.isnan(f) or math.isinf(f):
45305
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
135 raise TypeError("Cannot convert %r to %s." % (f, cls.__name__))
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
136 return cls(*f.as_integer_ratio())
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
137
45305
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
138 @classmethod
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
139 def from_decimal(cls, dec):
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
140 """Converts a finite Decimal instance to a rational number, exactly."""
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
141 from decimal import Decimal
47920
bd435e8b2e28 Issue 3285: Fractions from_float() and from_decimal() accept Integral arguments.
Raymond Hettinger <python@rcn.com>
parents: 47917
diff changeset
142 if isinstance(dec, numbers.Integral):
bd435e8b2e28 Issue 3285: Fractions from_float() and from_decimal() accept Integral arguments.
Raymond Hettinger <python@rcn.com>
parents: 47917
diff changeset
143 dec = Decimal(int(dec))
bd435e8b2e28 Issue 3285: Fractions from_float() and from_decimal() accept Integral arguments.
Raymond Hettinger <python@rcn.com>
parents: 47917
diff changeset
144 elif not isinstance(dec, Decimal):
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
145 raise TypeError(
45305
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
146 "%s.from_decimal() only takes Decimals, not %r (%s)" %
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
147 (cls.__name__, dec, type(dec).__name__))
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
148 if not dec.is_finite():
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
149 # Catches infinities and nans.
45305
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
150 raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
151 sign, digits, exp = dec.as_tuple()
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
152 digits = int(''.join(map(str, digits)))
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
153 if sign:
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
154 digits = -digits
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
155 if exp >= 0:
45305
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
156 return cls(digits * 10 ** exp)
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
157 else:
45305
d319f40cd000 Revert change in r60712: turn alternate constructors back into
Mark Dickinson <dickinsm@gmail.com>
parents: 45303
diff changeset
158 return cls(digits, 10 ** -exp)
44757
c4709b81abde Several tweaks: add construction from strings and .from_decimal(), change
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 44691
diff changeset
159
45303
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
160 def limit_denominator(self, max_denominator=1000000):
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
161 """Closest Fraction to self with denominator at most max_denominator.
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
162
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
163 >>> Fraction('3.141592653589793').limit_denominator(10)
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
164 Fraction(22, 7)
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
165 >>> Fraction('3.141592653589793').limit_denominator(100)
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
166 Fraction(311, 99)
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
167 >>> Fraction(1234, 5678).limit_denominator(10000)
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
168 Fraction(1234, 5678)
44899
cdc4aecedd4c Add first-cut at an approximation function (still needs rounding tweaks). Add continued fraction conversions.
Raymond Hettinger <python@rcn.com>
parents: 44757
diff changeset
169
45303
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
170 """
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
171 # Algorithm notes: For any real number x, define a *best upper
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
172 # approximation* to x to be a rational number p/q such that:
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
173 #
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
174 # (1) p/q >= x, and
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
175 # (2) if p/q > r/s >= x then s > q, for any rational r/s.
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
176 #
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
177 # Define *best lower approximation* similarly. Then it can be
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
178 # proved that a rational number is a best upper or lower
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
179 # approximation to x if, and only if, it is a convergent or
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
180 # semiconvergent of the (unique shortest) continued fraction
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
181 # associated to x.
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
182 #
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
183 # To find a best rational approximation with denominator <= M,
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
184 # we find the best upper and lower approximations with
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
185 # denominator <= M and take whichever of these is closer to x.
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
186 # In the event of a tie, the bound with smaller denominator is
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
187 # chosen. If both denominators are equal (which can happen
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
188 # only when max_denominator == 1 and self is midway between
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
189 # two integers) the lower bound---i.e., the floor of self, is
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
190 # taken.
44899
cdc4aecedd4c Add first-cut at an approximation function (still needs rounding tweaks). Add continued fraction conversions.
Raymond Hettinger <python@rcn.com>
parents: 44757
diff changeset
191
45303
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
192 if max_denominator < 1:
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
193 raise ValueError("max_denominator should be at least 1")
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
194 if self._denominator <= max_denominator:
45303
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
195 return Fraction(self)
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
196
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
197 p0, q0, p1, q1 = 0, 1, 1, 0
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
198 n, d = self._numerator, self._denominator
45303
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
199 while True:
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
200 a = n//d
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
201 q2 = q0+a*q1
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
202 if q2 > max_denominator:
44899
cdc4aecedd4c Add first-cut at an approximation function (still needs rounding tweaks). Add continued fraction conversions.
Raymond Hettinger <python@rcn.com>
parents: 44757
diff changeset
203 break
45303
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
204 p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
205 n, d = d, n-a*d
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
206
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
207 k = (max_denominator-q0)//q1
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
208 bound1 = Fraction(p0+k*p1, q0+k*q1)
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
209 bound2 = Fraction(p1, q1)
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
210 if abs(bound2 - self) <= abs(bound1-self):
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
211 return bound2
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
212 else:
d673d003b6ca Implementation of Fraction.limit_denominator.
Mark Dickinson <dickinsm@gmail.com>
parents: 45277
diff changeset
213 return bound1
44899
cdc4aecedd4c Add first-cut at an approximation function (still needs rounding tweaks). Add continued fraction conversions.
Raymond Hettinger <python@rcn.com>
parents: 44757
diff changeset
214
45080
678509f9a03f Roll back r60248. It's useful to encourage users not to change Rational
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45075
diff changeset
215 @property
678509f9a03f Roll back r60248. It's useful to encourage users not to change Rational
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45075
diff changeset
216 def numerator(a):
678509f9a03f Roll back r60248. It's useful to encourage users not to change Rational
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45075
diff changeset
217 return a._numerator
678509f9a03f Roll back r60248. It's useful to encourage users not to change Rational
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45075
diff changeset
218
678509f9a03f Roll back r60248. It's useful to encourage users not to change Rational
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45075
diff changeset
219 @property
678509f9a03f Roll back r60248. It's useful to encourage users not to change Rational
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45075
diff changeset
220 def denominator(a):
678509f9a03f Roll back r60248. It's useful to encourage users not to change Rational
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45075
diff changeset
221 return a._denominator
678509f9a03f Roll back r60248. It's useful to encourage users not to change Rational
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45075
diff changeset
222
28788
558689b6d7f0 Run these demo scripts through reindent.py to give them 4-space indents. I've verified that their output is unchanged.
Andrew M. Kuchling <amk@amk.ca>
parents: 28787
diff changeset
223 def __repr__(self):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
224 """repr(self)"""
47839
43f6bb0eacb2 Remove trailing 'L's from numerator and denominator in the
Mark Dickinson <dickinsm@gmail.com>
parents: 47793
diff changeset
225 return ('Fraction(%s, %s)' % (self._numerator, self._denominator))
1966
dd7be8128410 adapted to new overloading scheme
Guido van Rossum <guido@python.org>
parents: 1427
diff changeset
226
28788
558689b6d7f0 Run these demo scripts through reindent.py to give them 4-space indents. I've verified that their output is unchanged.
Andrew M. Kuchling <amk@amk.ca>
parents: 28787
diff changeset
227 def __str__(self):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
228 """str(self)"""
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
229 if self._denominator == 1:
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
230 return str(self._numerator)
28788
558689b6d7f0 Run these demo scripts through reindent.py to give them 4-space indents. I've verified that their output is unchanged.
Andrew M. Kuchling <amk@amk.ca>
parents: 28787
diff changeset
231 else:
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
232 return '%s/%s' % (self._numerator, self._denominator)
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
233
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
234 def _operator_fallbacks(monomorphic_operator, fallback_operator):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
235 """Generates forward and reverse operators given a purely-rational
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
236 operator and a function from the operator module.
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
237
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
238 Use this like:
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
239 __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
240
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
241 In general, we want to implement the arithmetic operations so
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
242 that mixed-mode operations either call an implementation whose
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
243 author knew about the types of both arguments, or convert both
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
244 to the nearest built in type and do the operation there. In
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
245 Fraction, that means that we define __add__ and __radd__ as:
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
246
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
247 def __add__(self, other):
45075
8659e52614da Minor wordsmithing on docstring
Raymond Hettinger <python@rcn.com>
parents: 45073
diff changeset
248 # Both types have numerators/denominator attributes,
8659e52614da Minor wordsmithing on docstring
Raymond Hettinger <python@rcn.com>
parents: 45073
diff changeset
249 # so do the operation directly
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
250 if isinstance(other, (int, long, Fraction)):
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
251 return Fraction(self.numerator * other.denominator +
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
252 other.numerator * self.denominator,
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
253 self.denominator * other.denominator)
45075
8659e52614da Minor wordsmithing on docstring
Raymond Hettinger <python@rcn.com>
parents: 45073
diff changeset
254 # float and complex don't have those operations, but we
8659e52614da Minor wordsmithing on docstring
Raymond Hettinger <python@rcn.com>
parents: 45073
diff changeset
255 # know about those types, so special case them.
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
256 elif isinstance(other, float):
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
257 return float(self) + other
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
258 elif isinstance(other, complex):
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
259 return complex(self) + other
45075
8659e52614da Minor wordsmithing on docstring
Raymond Hettinger <python@rcn.com>
parents: 45073
diff changeset
260 # Let the other type take over.
8659e52614da Minor wordsmithing on docstring
Raymond Hettinger <python@rcn.com>
parents: 45073
diff changeset
261 return NotImplemented
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
262
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
263 def __radd__(self, other):
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
264 # radd handles more types than add because there's
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
265 # nothing left to fall back to.
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
266 if isinstance(other, Rational):
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
267 return Fraction(self.numerator * other.denominator +
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
268 other.numerator * self.denominator,
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
269 self.denominator * other.denominator)
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
270 elif isinstance(other, Real):
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
271 return float(other) + float(self)
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
272 elif isinstance(other, Complex):
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
273 return complex(other) + complex(self)
45075
8659e52614da Minor wordsmithing on docstring
Raymond Hettinger <python@rcn.com>
parents: 45073
diff changeset
274 return NotImplemented
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
275
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
276
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
277 There are 5 different cases for a mixed-type addition on
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
278 Fraction. I'll refer to all of the above code that doesn't
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
279 refer to Fraction, float, or complex as "boilerplate". 'r'
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
280 will be an instance of Fraction, which is a subtype of
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
281 Rational (r : Fraction <: Rational), and b : B <:
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
282 Complex. The first three involve 'r + b':
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
283
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
284 1. If B <: Fraction, int, float, or complex, we handle
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
285 that specially, and all is well.
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
286 2. If Fraction falls back to the boilerplate code, and it
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
287 were to return a value from __add__, we'd miss the
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
288 possibility that B defines a more intelligent __radd__,
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
289 so the boilerplate should return NotImplemented from
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
290 __add__. In particular, we don't handle Rational
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
291 here, even though we could get an exact answer, in case
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
292 the other type wants to do something special.
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
293 3. If B <: Fraction, Python tries B.__radd__ before
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
294 Fraction.__add__. This is ok, because it was
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
295 implemented with knowledge of Fraction, so it can
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
296 handle those instances before delegating to Real or
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
297 Complex.
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
298
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
299 The next two situations describe 'b + r'. We assume that b
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
300 didn't know about Fraction in its implementation, and that it
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
301 uses similar boilerplate code:
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
302
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
303 4. If B <: Rational, then __radd_ converts both to the
45070
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
304 builtin rational type (hey look, that's us) and
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
305 proceeds.
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
306 5. Otherwise, __radd__ tries to find the nearest common
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
307 base ABC, and fall back to its builtin type. Since this
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
308 class doesn't subclass a concrete type, there's no
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
309 implementation to fall back to, so we need to try as
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
310 hard as possible to return an actual value, or the user
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
311 will get a TypeError.
03e4a36a56bb Added more documentation on how mixed-mode arithmetic should be implemented. I
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45024
diff changeset
312
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
313 """
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
314 def forward(a, b):
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
315 if isinstance(b, (int, long, Fraction)):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
316 return monomorphic_operator(a, b)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
317 elif isinstance(b, float):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
318 return fallback_operator(float(a), b)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
319 elif isinstance(b, complex):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
320 return fallback_operator(complex(a), b)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
321 else:
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
322 return NotImplemented
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
323 forward.__name__ = '__' + fallback_operator.__name__ + '__'
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
324 forward.__doc__ = monomorphic_operator.__doc__
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
325
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
326 def reverse(b, a):
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
327 if isinstance(a, Rational):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
328 # Includes ints.
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
329 return monomorphic_operator(a, b)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
330 elif isinstance(a, numbers.Real):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
331 return fallback_operator(float(a), float(b))
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
332 elif isinstance(a, numbers.Complex):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
333 return fallback_operator(complex(a), complex(b))
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
334 else:
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
335 return NotImplemented
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
336 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
337 reverse.__doc__ = monomorphic_operator.__doc__
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
338
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
339 return forward, reverse
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
340
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
341 def _add(a, b):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
342 """a + b"""
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
343 return Fraction(a.numerator * b.denominator +
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
344 b.numerator * a.denominator,
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
345 a.denominator * b.denominator)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
346
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
347 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
348
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
349 def _sub(a, b):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
350 """a - b"""
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
351 return Fraction(a.numerator * b.denominator -
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
352 b.numerator * a.denominator,
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
353 a.denominator * b.denominator)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
354
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
355 __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
356
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
357 def _mul(a, b):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
358 """a * b"""
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
359 return Fraction(a.numerator * b.numerator, a.denominator * b.denominator)
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
360
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
361 __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
362
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
363 def _div(a, b):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
364 """a / b"""
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
365 return Fraction(a.numerator * b.denominator,
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
366 a.denominator * b.numerator)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
367
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
368 __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
369 __div__, __rdiv__ = _operator_fallbacks(_div, operator.div)
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
370
44932
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
371 def __floordiv__(a, b):
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
372 """a // b"""
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
373 # Will be math.floor(a / b) in 3.0.
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
374 div = a / b
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
375 if isinstance(div, Rational):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
376 # trunc(math.floor(div)) doesn't work if the rational is
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
377 # more precise than a float because the intermediate
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
378 # rounding may cross an integer boundary.
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
379 return div.numerator // div.denominator
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
380 else:
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
381 return math.floor(div)
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
382
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
383 def __rfloordiv__(b, a):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
384 """a // b"""
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
385 # Will be math.floor(a / b) in 3.0.
44932
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
386 div = a / b
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
387 if isinstance(div, Rational):
44932
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
388 # trunc(math.floor(div)) doesn't work if the rational is
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
389 # more precise than a float because the intermediate
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
390 # rounding may cross an integer boundary.
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
391 return div.numerator // div.denominator
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
392 else:
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
393 return math.floor(div)
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
394
44932
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
395 def __mod__(a, b):
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
396 """a % b"""
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
397 div = a // b
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
398 return a - b * div
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
399
28788
558689b6d7f0 Run these demo scripts through reindent.py to give them 4-space indents. I've verified that their output is unchanged.
Andrew M. Kuchling <amk@amk.ca>
parents: 28787
diff changeset
400 def __rmod__(b, a):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
401 """a % b"""
44932
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
402 div = a // b
ce159d01ee32 More code cleanup. Remove unnecessary indirection to useless class methods.
Raymond Hettinger <python@rcn.com>
parents: 44925
diff changeset
403 return a - b * div
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
404
28788
558689b6d7f0 Run these demo scripts through reindent.py to give them 4-space indents. I've verified that their output is unchanged.
Andrew M. Kuchling <amk@amk.ca>
parents: 28787
diff changeset
405 def __pow__(a, b):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
406 """a ** b
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
407
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
408 If b is not an integer, the result will be a float or complex
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
409 since roots are generally irrational. If b is an integer, the
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
410 result will be rational.
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
411
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
412 """
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
413 if isinstance(b, Rational):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
414 if b.denominator == 1:
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
415 power = b.numerator
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
416 if power >= 0:
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
417 return Fraction(a._numerator ** power,
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
418 a._denominator ** power)
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
419 else:
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
420 return Fraction(a._denominator ** -power,
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
421 a._numerator ** -power)
28788
558689b6d7f0 Run these demo scripts through reindent.py to give them 4-space indents. I've verified that their output is unchanged.
Andrew M. Kuchling <amk@amk.ca>
parents: 28787
diff changeset
422 else:
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
423 # A fractional power will generally produce an
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
424 # irrational number.
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
425 return float(a) ** float(b)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
426 else:
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
427 return float(a) ** b
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
428
28788
558689b6d7f0 Run these demo scripts through reindent.py to give them 4-space indents. I've verified that their output is unchanged.
Andrew M. Kuchling <amk@amk.ca>
parents: 28787
diff changeset
429 def __rpow__(b, a):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
430 """a ** b"""
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
431 if b._denominator == 1 and b._numerator >= 0:
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
432 # If a is an int, keep it that way if possible.
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
433 return a ** b._numerator
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
434
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
435 if isinstance(a, Rational):
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
436 return Fraction(a.numerator, a.denominator) ** b
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
437
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
438 if b._denominator == 1:
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
439 return a ** b._numerator
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
440
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
441 return a ** float(b)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
442
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
443 def __pos__(a):
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
444 """+a: Coerces a subclass instance to Fraction"""
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
445 return Fraction(a._numerator, a._denominator)
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
446
28788
558689b6d7f0 Run these demo scripts through reindent.py to give them 4-space indents. I've verified that their output is unchanged.
Andrew M. Kuchling <amk@amk.ca>
parents: 28787
diff changeset
447 def __neg__(a):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
448 """-a"""
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
449 return Fraction(-a._numerator, a._denominator)
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
450
28788
558689b6d7f0 Run these demo scripts through reindent.py to give them 4-space indents. I've verified that their output is unchanged.
Andrew M. Kuchling <amk@amk.ca>
parents: 28787
diff changeset
451 def __abs__(a):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
452 """abs(a)"""
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
453 return Fraction(abs(a._numerator), a._denominator)
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
454
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
455 def __trunc__(a):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
456 """trunc(a)"""
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
457 if a._numerator < 0:
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
458 return -(-a._numerator // a._denominator)
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
459 else:
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
460 return a._numerator // a._denominator
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
461
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
462 def __hash__(self):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
463 """hash(self)
945
465b9841770e Initial revision
Guido van Rossum <guido@python.org>
parents:
diff changeset
464
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
465 Tricky because values that are exactly representable as a
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
466 float must have the same hash as that float.
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
467
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
468 """
44934
3bd19c8af2b1 Mark todos and review comments.
Raymond Hettinger <python@rcn.com>
parents: 44933
diff changeset
469 # XXX since this method is expensive, consider caching the result
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
470 if self._denominator == 1:
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
471 # Get integers right.
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
472 return hash(self._numerator)
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
473 # Expensive check, but definitely correct.
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
474 if self == float(self):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
475 return hash(float(self))
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
476 else:
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
477 # Use tuple's hash to avoid a high collision rate on
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
478 # simple fractions.
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
479 return hash((self._numerator, self._denominator))
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
480
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
481 def __eq__(a, b):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
482 """a == b"""
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
483 if isinstance(b, Rational):
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
484 return (a._numerator == b.numerator and
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
485 a._denominator == b.denominator)
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
486 if isinstance(b, numbers.Complex) and b.imag == 0:
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
487 b = b.real
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
488 if isinstance(b, float):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
489 return a == a.from_float(b)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
490 else:
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
491 # XXX: If b.__eq__ is implemented like this method, it may
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
492 # give the wrong answer after float(a) changes a's
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
493 # value. Better ways of doing this are welcome.
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
494 return float(a) == b
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
495
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
496 def _subtractAndCompareToZero(a, b, op):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
497 """Helper function for comparison operators.
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
498
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
499 Subtracts b from a, exactly if possible, and compares the
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
500 result with 0 using op, in such a way that the comparison
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
501 won't recurse. If the difference raises a TypeError, returns
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
502 NotImplemented instead.
5503
ba005e4db4c5 A completely new Rat.py by Sjoerd.
Guido van Rossum <guido@python.org>
parents: 1966
diff changeset
503
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
504 """
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
505 if isinstance(b, numbers.Complex) and b.imag == 0:
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
506 b = b.real
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
507 if isinstance(b, float):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
508 b = a.from_float(b)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
509 try:
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
510 # XXX: If b <: Real but not <: Rational, this is likely
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
511 # to fall back to a float. If the actual values differ by
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
512 # less than MIN_FLOAT, this could falsely call them equal,
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
513 # which would make <= inconsistent with ==. Better ways of
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
514 # doing this are welcome.
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
515 diff = a - b
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
516 except TypeError:
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
517 return NotImplemented
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
518 if isinstance(diff, Rational):
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
519 return op(diff.numerator, 0)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
520 return op(diff, 0)
28786
8a6e4c92bd7f Avoid TypeError by not comparing complex numbers
Andrew M. Kuchling <amk@amk.ca>
parents: 9077
diff changeset
521
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
522 def __lt__(a, b):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
523 """a < b"""
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
524 return a._subtractAndCompareToZero(b, operator.lt)
945
465b9841770e Initial revision
Guido van Rossum <guido@python.org>
parents:
diff changeset
525
44691
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
526 def __gt__(a, b):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
527 """a > b"""
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
528 return a._subtractAndCompareToZero(b, operator.gt)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
529
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
530 def __le__(a, b):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
531 """a <= b"""
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
532 return a._subtractAndCompareToZero(b, operator.le)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
533
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
534 def __ge__(a, b):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
535 """a >= b"""
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
536 return a._subtractAndCompareToZero(b, operator.ge)
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
537
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
538 def __nonzero__(a):
46e731bb6a85 Add rational.Rational as an implementation of numbers.Rational with infinite
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 28788
diff changeset
539 """a != 0"""
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
540 return a._numerator != 0
44933
6da0eea36783 Add support for copy, deepcopy, and pickle.
Raymond Hettinger <python@rcn.com>
parents: 44932
diff changeset
541
6da0eea36783 Add support for copy, deepcopy, and pickle.
Raymond Hettinger <python@rcn.com>
parents: 44932
diff changeset
542 # support for pickling, copy, and deepcopy
6da0eea36783 Add support for copy, deepcopy, and pickle.
Raymond Hettinger <python@rcn.com>
parents: 44932
diff changeset
543
6da0eea36783 Add support for copy, deepcopy, and pickle.
Raymond Hettinger <python@rcn.com>
parents: 44932
diff changeset
544 def __reduce__(self):
6da0eea36783 Add support for copy, deepcopy, and pickle.
Raymond Hettinger <python@rcn.com>
parents: 44932
diff changeset
545 return (self.__class__, (str(self),))
6da0eea36783 Add support for copy, deepcopy, and pickle.
Raymond Hettinger <python@rcn.com>
parents: 44932
diff changeset
546
6da0eea36783 Add support for copy, deepcopy, and pickle.
Raymond Hettinger <python@rcn.com>
parents: 44932
diff changeset
547 def __copy__(self):
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
548 if type(self) == Fraction:
44933
6da0eea36783 Add support for copy, deepcopy, and pickle.
Raymond Hettinger <python@rcn.com>
parents: 44932
diff changeset
549 return self # I'm immutable; therefore I am my own clone
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
550 return self.__class__(self._numerator, self._denominator)
44933
6da0eea36783 Add support for copy, deepcopy, and pickle.
Raymond Hettinger <python@rcn.com>
parents: 44932
diff changeset
551
6da0eea36783 Add support for copy, deepcopy, and pickle.
Raymond Hettinger <python@rcn.com>
parents: 44932
diff changeset
552 def __deepcopy__(self, memo):
45275
a50c1fb7d920 Rename rational.Rational to fractions.Fraction, to avoid name clash
Mark Dickinson <dickinsm@gmail.com>
parents: 45266
diff changeset
553 if type(self) == Fraction:
44933
6da0eea36783 Add support for copy, deepcopy, and pickle.
Raymond Hettinger <python@rcn.com>
parents: 44932
diff changeset
554 return self # My components are also immutable
45332
4fcb700115d8 Change simple instances (in Fraction) of self.numerator and self.denominator to
Jeffrey Yasskin <jyasskin@gmail.com>
parents: 45331
diff changeset
555 return self.__class__(self._numerator, self._denominator)