# Python code coverage for Lib/fractions.py

# | count | content |
---|---|---|

1 | n/a | # Originally contributed by Sjoerd Mullender. |

2 | n/a | # Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>. |

3 | n/a | |

4 | n/a | """Fraction, infinite-precision, real numbers.""" |

5 | n/a | |

6 | n/a | from decimal import Decimal |

7 | n/a | import math |

8 | n/a | import numbers |

9 | n/a | import operator |

10 | n/a | import re |

11 | n/a | import sys |

12 | n/a | |

13 | n/a | __all__ = ['Fraction', 'gcd'] |

14 | n/a | |

15 | n/a | |

16 | n/a | |

17 | n/a | def gcd(a, b): |

18 | n/a | """Calculate the Greatest Common Divisor of a and b. |

19 | n/a | |

20 | n/a | Unless b==0, the result will have the same sign as b (so that when |

21 | n/a | b is divided by it, the result comes out positive). |

22 | n/a | """ |

23 | n/a | import warnings |

24 | n/a | warnings.warn('fractions.gcd() is deprecated. Use math.gcd() instead.', |

25 | n/a | DeprecationWarning, 2) |

26 | n/a | if type(a) is int is type(b): |

27 | n/a | if (b or a) < 0: |

28 | n/a | return -math.gcd(a, b) |

29 | n/a | return math.gcd(a, b) |

30 | n/a | return _gcd(a, b) |

31 | n/a | |

32 | n/a | def _gcd(a, b): |

33 | n/a | # Supports non-integers for backward compatibility. |

34 | n/a | while b: |

35 | n/a | a, b = b, a%b |

36 | n/a | return a |

37 | n/a | |

38 | n/a | # Constants related to the hash implementation; hash(x) is based |

39 | n/a | # on the reduction of x modulo the prime _PyHASH_MODULUS. |

40 | n/a | _PyHASH_MODULUS = sys.hash_info.modulus |

41 | n/a | # Value to be used for rationals that reduce to infinity modulo |

42 | n/a | # _PyHASH_MODULUS. |

43 | n/a | _PyHASH_INF = sys.hash_info.inf |

44 | n/a | |

45 | n/a | _RATIONAL_FORMAT = re.compile(r""" |

46 | n/a | \A\s* # optional whitespace at the start, then |

47 | n/a | (?P<sign>[-+]?) # an optional sign, then |

48 | n/a | (?=\d|\.\d) # lookahead for digit or .digit |

49 | n/a | (?P<num>\d*) # numerator (possibly empty) |

50 | n/a | (?: # followed by |

51 | n/a | (?:/(?P<denom>\d+))? # an optional denominator |

52 | n/a | | # or |

53 | n/a | (?:\.(?P<decimal>\d*))? # an optional fractional part |

54 | n/a | (?:E(?P<exp>[-+]?\d+))? # and optional exponent |

55 | n/a | ) |

56 | n/a | \s*\Z # and optional whitespace to finish |

57 | n/a | """, re.VERBOSE | re.IGNORECASE) |

58 | n/a | |

59 | n/a | |

60 | n/a | class Fraction(numbers.Rational): |

61 | n/a | """This class implements rational numbers. |

62 | n/a | |

63 | n/a | In the two-argument form of the constructor, Fraction(8, 6) will |

64 | n/a | produce a rational number equivalent to 4/3. Both arguments must |

65 | n/a | be Rational. The numerator defaults to 0 and the denominator |

66 | n/a | defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. |

67 | n/a | |

68 | n/a | Fractions can also be constructed from: |

69 | n/a | |

70 | n/a | - numeric strings similar to those accepted by the |

71 | n/a | float constructor (for example, '-2.3' or '1e10') |

72 | n/a | |

73 | n/a | - strings of the form '123/456' |

74 | n/a | |

75 | n/a | - float and Decimal instances |

76 | n/a | |

77 | n/a | - other Rational instances (including integers) |

78 | n/a | |

79 | n/a | """ |

80 | n/a | |

81 | n/a | __slots__ = ('_numerator', '_denominator') |

82 | n/a | |

83 | n/a | # We're immutable, so use __new__ not __init__ |

84 | n/a | def __new__(cls, numerator=0, denominator=None, *, _normalize=True): |

85 | n/a | """Constructs a Rational. |

86 | n/a | |

87 | n/a | Takes a string like '3/2' or '1.5', another Rational instance, a |

88 | n/a | numerator/denominator pair, or a float. |

89 | n/a | |

90 | n/a | Examples |

91 | n/a | -------- |

92 | n/a | |

93 | n/a | >>> Fraction(10, -8) |

94 | n/a | Fraction(-5, 4) |

95 | n/a | >>> Fraction(Fraction(1, 7), 5) |

96 | n/a | Fraction(1, 35) |

97 | n/a | >>> Fraction(Fraction(1, 7), Fraction(2, 3)) |

98 | n/a | Fraction(3, 14) |

99 | n/a | >>> Fraction('314') |

100 | n/a | Fraction(314, 1) |

101 | n/a | >>> Fraction('-35/4') |

102 | n/a | Fraction(-35, 4) |

103 | n/a | >>> Fraction('3.1415') # conversion from numeric string |

104 | n/a | Fraction(6283, 2000) |

105 | n/a | >>> Fraction('-47e-2') # string may include a decimal exponent |

106 | n/a | Fraction(-47, 100) |

107 | n/a | >>> Fraction(1.47) # direct construction from float (exact conversion) |

108 | n/a | Fraction(6620291452234629, 4503599627370496) |

109 | n/a | >>> Fraction(2.25) |

110 | n/a | Fraction(9, 4) |

111 | n/a | >>> Fraction(Decimal('1.47')) |

112 | n/a | Fraction(147, 100) |

113 | n/a | |

114 | n/a | """ |

115 | n/a | self = super(Fraction, cls).__new__(cls) |

116 | n/a | |

117 | n/a | if denominator is None: |

118 | n/a | if type(numerator) is int: |

119 | n/a | self._numerator = numerator |

120 | n/a | self._denominator = 1 |

121 | n/a | return self |

122 | n/a | |

123 | n/a | elif isinstance(numerator, numbers.Rational): |

124 | n/a | self._numerator = numerator.numerator |

125 | n/a | self._denominator = numerator.denominator |

126 | n/a | return self |

127 | n/a | |

128 | n/a | elif isinstance(numerator, (float, Decimal)): |

129 | n/a | # Exact conversion |

130 | n/a | self._numerator, self._denominator = numerator.as_integer_ratio() |

131 | n/a | return self |

132 | n/a | |

133 | n/a | elif isinstance(numerator, str): |

134 | n/a | # Handle construction from strings. |

135 | n/a | m = _RATIONAL_FORMAT.match(numerator) |

136 | n/a | if m is None: |

137 | n/a | raise ValueError('Invalid literal for Fraction: %r' % |

138 | n/a | numerator) |

139 | n/a | numerator = int(m.group('num') or '0') |

140 | n/a | denom = m.group('denom') |

141 | n/a | if denom: |

142 | n/a | denominator = int(denom) |

143 | n/a | else: |

144 | n/a | denominator = 1 |

145 | n/a | decimal = m.group('decimal') |

146 | n/a | if decimal: |

147 | n/a | scale = 10**len(decimal) |

148 | n/a | numerator = numerator * scale + int(decimal) |

149 | n/a | denominator *= scale |

150 | n/a | exp = m.group('exp') |

151 | n/a | if exp: |

152 | n/a | exp = int(exp) |

153 | n/a | if exp >= 0: |

154 | n/a | numerator *= 10**exp |

155 | n/a | else: |

156 | n/a | denominator *= 10**-exp |

157 | n/a | if m.group('sign') == '-': |

158 | n/a | numerator = -numerator |

159 | n/a | |

160 | n/a | else: |

161 | n/a | raise TypeError("argument should be a string " |

162 | n/a | "or a Rational instance") |

163 | n/a | |

164 | n/a | elif type(numerator) is int is type(denominator): |

165 | n/a | pass # *very* normal case |

166 | n/a | |

167 | n/a | elif (isinstance(numerator, numbers.Rational) and |

168 | n/a | isinstance(denominator, numbers.Rational)): |

169 | n/a | numerator, denominator = ( |

170 | n/a | numerator.numerator * denominator.denominator, |

171 | n/a | denominator.numerator * numerator.denominator |

172 | n/a | ) |

173 | n/a | else: |

174 | n/a | raise TypeError("both arguments should be " |

175 | n/a | "Rational instances") |

176 | n/a | |

177 | n/a | if denominator == 0: |

178 | n/a | raise ZeroDivisionError('Fraction(%s, 0)' % numerator) |

179 | n/a | if _normalize: |

180 | n/a | if type(numerator) is int is type(denominator): |

181 | n/a | # *very* normal case |

182 | n/a | g = math.gcd(numerator, denominator) |

183 | n/a | if denominator < 0: |

184 | n/a | g = -g |

185 | n/a | else: |

186 | n/a | g = _gcd(numerator, denominator) |

187 | n/a | numerator //= g |

188 | n/a | denominator //= g |

189 | n/a | self._numerator = numerator |

190 | n/a | self._denominator = denominator |

191 | n/a | return self |

192 | n/a | |

193 | n/a | @classmethod |

194 | n/a | def from_float(cls, f): |

195 | n/a | """Converts a finite float to a rational number, exactly. |

196 | n/a | |

197 | n/a | Beware that Fraction.from_float(0.3) != Fraction(3, 10). |

198 | n/a | |

199 | n/a | """ |

200 | n/a | if isinstance(f, numbers.Integral): |

201 | n/a | return cls(f) |

202 | n/a | elif not isinstance(f, float): |

203 | n/a | raise TypeError("%s.from_float() only takes floats, not %r (%s)" % |

204 | n/a | (cls.__name__, f, type(f).__name__)) |

205 | n/a | return cls(*f.as_integer_ratio()) |

206 | n/a | |

207 | n/a | @classmethod |

208 | n/a | def from_decimal(cls, dec): |

209 | n/a | """Converts a finite Decimal instance to a rational number, exactly.""" |

210 | n/a | from decimal import Decimal |

211 | n/a | if isinstance(dec, numbers.Integral): |

212 | n/a | dec = Decimal(int(dec)) |

213 | n/a | elif not isinstance(dec, Decimal): |

214 | n/a | raise TypeError( |

215 | n/a | "%s.from_decimal() only takes Decimals, not %r (%s)" % |

216 | n/a | (cls.__name__, dec, type(dec).__name__)) |

217 | n/a | return cls(*dec.as_integer_ratio()) |

218 | n/a | |

219 | n/a | def limit_denominator(self, max_denominator=1000000): |

220 | n/a | """Closest Fraction to self with denominator at most max_denominator. |

221 | n/a | |

222 | n/a | >>> Fraction('3.141592653589793').limit_denominator(10) |

223 | n/a | Fraction(22, 7) |

224 | n/a | >>> Fraction('3.141592653589793').limit_denominator(100) |

225 | n/a | Fraction(311, 99) |

226 | n/a | >>> Fraction(4321, 8765).limit_denominator(10000) |

227 | n/a | Fraction(4321, 8765) |

228 | n/a | |

229 | n/a | """ |

230 | n/a | # Algorithm notes: For any real number x, define a *best upper |

231 | n/a | # approximation* to x to be a rational number p/q such that: |

232 | n/a | # |

233 | n/a | # (1) p/q >= x, and |

234 | n/a | # (2) if p/q > r/s >= x then s > q, for any rational r/s. |

235 | n/a | # |

236 | n/a | # Define *best lower approximation* similarly. Then it can be |

237 | n/a | # proved that a rational number is a best upper or lower |

238 | n/a | # approximation to x if, and only if, it is a convergent or |

239 | n/a | # semiconvergent of the (unique shortest) continued fraction |

240 | n/a | # associated to x. |

241 | n/a | # |

242 | n/a | # To find a best rational approximation with denominator <= M, |

243 | n/a | # we find the best upper and lower approximations with |

244 | n/a | # denominator <= M and take whichever of these is closer to x. |

245 | n/a | # In the event of a tie, the bound with smaller denominator is |

246 | n/a | # chosen. If both denominators are equal (which can happen |

247 | n/a | # only when max_denominator == 1 and self is midway between |

248 | n/a | # two integers) the lower bound---i.e., the floor of self, is |

249 | n/a | # taken. |

250 | n/a | |

251 | n/a | if max_denominator < 1: |

252 | n/a | raise ValueError("max_denominator should be at least 1") |

253 | n/a | if self._denominator <= max_denominator: |

254 | n/a | return Fraction(self) |

255 | n/a | |

256 | n/a | p0, q0, p1, q1 = 0, 1, 1, 0 |

257 | n/a | n, d = self._numerator, self._denominator |

258 | n/a | while True: |

259 | n/a | a = n//d |

260 | n/a | q2 = q0+a*q1 |

261 | n/a | if q2 > max_denominator: |

262 | n/a | break |

263 | n/a | p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 |

264 | n/a | n, d = d, n-a*d |

265 | n/a | |

266 | n/a | k = (max_denominator-q0)//q1 |

267 | n/a | bound1 = Fraction(p0+k*p1, q0+k*q1) |

268 | n/a | bound2 = Fraction(p1, q1) |

269 | n/a | if abs(bound2 - self) <= abs(bound1-self): |

270 | n/a | return bound2 |

271 | n/a | else: |

272 | n/a | return bound1 |

273 | n/a | |

274 | n/a | @property |

275 | n/a | def numerator(a): |

276 | n/a | return a._numerator |

277 | n/a | |

278 | n/a | @property |

279 | n/a | def denominator(a): |

280 | n/a | return a._denominator |

281 | n/a | |

282 | n/a | def __repr__(self): |

283 | n/a | """repr(self)""" |

284 | n/a | return '%s(%s, %s)' % (self.__class__.__name__, |

285 | n/a | self._numerator, self._denominator) |

286 | n/a | |

287 | n/a | def __str__(self): |

288 | n/a | """str(self)""" |

289 | n/a | if self._denominator == 1: |

290 | n/a | return str(self._numerator) |

291 | n/a | else: |

292 | n/a | return '%s/%s' % (self._numerator, self._denominator) |

293 | n/a | |

294 | n/a | def _operator_fallbacks(monomorphic_operator, fallback_operator): |

295 | n/a | """Generates forward and reverse operators given a purely-rational |

296 | n/a | operator and a function from the operator module. |

297 | n/a | |

298 | n/a | Use this like: |

299 | n/a | __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) |

300 | n/a | |

301 | n/a | In general, we want to implement the arithmetic operations so |

302 | n/a | that mixed-mode operations either call an implementation whose |

303 | n/a | author knew about the types of both arguments, or convert both |

304 | n/a | to the nearest built in type and do the operation there. In |

305 | n/a | Fraction, that means that we define __add__ and __radd__ as: |

306 | n/a | |

307 | n/a | def __add__(self, other): |

308 | n/a | # Both types have numerators/denominator attributes, |

309 | n/a | # so do the operation directly |

310 | n/a | if isinstance(other, (int, Fraction)): |

311 | n/a | return Fraction(self.numerator * other.denominator + |

312 | n/a | other.numerator * self.denominator, |

313 | n/a | self.denominator * other.denominator) |

314 | n/a | # float and complex don't have those operations, but we |

315 | n/a | # know about those types, so special case them. |

316 | n/a | elif isinstance(other, float): |

317 | n/a | return float(self) + other |

318 | n/a | elif isinstance(other, complex): |

319 | n/a | return complex(self) + other |

320 | n/a | # Let the other type take over. |

321 | n/a | return NotImplemented |

322 | n/a | |

323 | n/a | def __radd__(self, other): |

324 | n/a | # radd handles more types than add because there's |

325 | n/a | # nothing left to fall back to. |

326 | n/a | if isinstance(other, numbers.Rational): |

327 | n/a | return Fraction(self.numerator * other.denominator + |

328 | n/a | other.numerator * self.denominator, |

329 | n/a | self.denominator * other.denominator) |

330 | n/a | elif isinstance(other, Real): |

331 | n/a | return float(other) + float(self) |

332 | n/a | elif isinstance(other, Complex): |

333 | n/a | return complex(other) + complex(self) |

334 | n/a | return NotImplemented |

335 | n/a | |

336 | n/a | |

337 | n/a | There are 5 different cases for a mixed-type addition on |

338 | n/a | Fraction. I'll refer to all of the above code that doesn't |

339 | n/a | refer to Fraction, float, or complex as "boilerplate". 'r' |

340 | n/a | will be an instance of Fraction, which is a subtype of |

341 | n/a | Rational (r : Fraction <: Rational), and b : B <: |

342 | n/a | Complex. The first three involve 'r + b': |

343 | n/a | |

344 | n/a | 1. If B <: Fraction, int, float, or complex, we handle |

345 | n/a | that specially, and all is well. |

346 | n/a | 2. If Fraction falls back to the boilerplate code, and it |

347 | n/a | were to return a value from __add__, we'd miss the |

348 | n/a | possibility that B defines a more intelligent __radd__, |

349 | n/a | so the boilerplate should return NotImplemented from |

350 | n/a | __add__. In particular, we don't handle Rational |

351 | n/a | here, even though we could get an exact answer, in case |

352 | n/a | the other type wants to do something special. |

353 | n/a | 3. If B <: Fraction, Python tries B.__radd__ before |

354 | n/a | Fraction.__add__. This is ok, because it was |

355 | n/a | implemented with knowledge of Fraction, so it can |

356 | n/a | handle those instances before delegating to Real or |

357 | n/a | Complex. |

358 | n/a | |

359 | n/a | The next two situations describe 'b + r'. We assume that b |

360 | n/a | didn't know about Fraction in its implementation, and that it |

361 | n/a | uses similar boilerplate code: |

362 | n/a | |

363 | n/a | 4. If B <: Rational, then __radd_ converts both to the |

364 | n/a | builtin rational type (hey look, that's us) and |

365 | n/a | proceeds. |

366 | n/a | 5. Otherwise, __radd__ tries to find the nearest common |

367 | n/a | base ABC, and fall back to its builtin type. Since this |

368 | n/a | class doesn't subclass a concrete type, there's no |

369 | n/a | implementation to fall back to, so we need to try as |

370 | n/a | hard as possible to return an actual value, or the user |

371 | n/a | will get a TypeError. |

372 | n/a | |

373 | n/a | """ |

374 | n/a | def forward(a, b): |

375 | n/a | if isinstance(b, (int, Fraction)): |

376 | n/a | return monomorphic_operator(a, b) |

377 | n/a | elif isinstance(b, float): |

378 | n/a | return fallback_operator(float(a), b) |

379 | n/a | elif isinstance(b, complex): |

380 | n/a | return fallback_operator(complex(a), b) |

381 | n/a | else: |

382 | n/a | return NotImplemented |

383 | n/a | forward.__name__ = '__' + fallback_operator.__name__ + '__' |

384 | n/a | forward.__doc__ = monomorphic_operator.__doc__ |

385 | n/a | |

386 | n/a | def reverse(b, a): |

387 | n/a | if isinstance(a, numbers.Rational): |

388 | n/a | # Includes ints. |

389 | n/a | return monomorphic_operator(a, b) |

390 | n/a | elif isinstance(a, numbers.Real): |

391 | n/a | return fallback_operator(float(a), float(b)) |

392 | n/a | elif isinstance(a, numbers.Complex): |

393 | n/a | return fallback_operator(complex(a), complex(b)) |

394 | n/a | else: |

395 | n/a | return NotImplemented |

396 | n/a | reverse.__name__ = '__r' + fallback_operator.__name__ + '__' |

397 | n/a | reverse.__doc__ = monomorphic_operator.__doc__ |

398 | n/a | |

399 | n/a | return forward, reverse |

400 | n/a | |

401 | n/a | def _add(a, b): |

402 | n/a | """a + b""" |

403 | n/a | da, db = a.denominator, b.denominator |

404 | n/a | return Fraction(a.numerator * db + b.numerator * da, |

405 | n/a | da * db) |

406 | n/a | |

407 | n/a | __add__, __radd__ = _operator_fallbacks(_add, operator.add) |

408 | n/a | |

409 | n/a | def _sub(a, b): |

410 | n/a | """a - b""" |

411 | n/a | da, db = a.denominator, b.denominator |

412 | n/a | return Fraction(a.numerator * db - b.numerator * da, |

413 | n/a | da * db) |

414 | n/a | |

415 | n/a | __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) |

416 | n/a | |

417 | n/a | def _mul(a, b): |

418 | n/a | """a * b""" |

419 | n/a | return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) |

420 | n/a | |

421 | n/a | __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) |

422 | n/a | |

423 | n/a | def _div(a, b): |

424 | n/a | """a / b""" |

425 | n/a | return Fraction(a.numerator * b.denominator, |

426 | n/a | a.denominator * b.numerator) |

427 | n/a | |

428 | n/a | __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) |

429 | n/a | |

430 | n/a | def __floordiv__(a, b): |

431 | n/a | """a // b""" |

432 | n/a | return math.floor(a / b) |

433 | n/a | |

434 | n/a | def __rfloordiv__(b, a): |

435 | n/a | """a // b""" |

436 | n/a | return math.floor(a / b) |

437 | n/a | |

438 | n/a | def __mod__(a, b): |

439 | n/a | """a % b""" |

440 | n/a | div = a // b |

441 | n/a | return a - b * div |

442 | n/a | |

443 | n/a | def __rmod__(b, a): |

444 | n/a | """a % b""" |

445 | n/a | div = a // b |

446 | n/a | return a - b * div |

447 | n/a | |

448 | n/a | def __pow__(a, b): |

449 | n/a | """a ** b |

450 | n/a | |

451 | n/a | If b is not an integer, the result will be a float or complex |

452 | n/a | since roots are generally irrational. If b is an integer, the |

453 | n/a | result will be rational. |

454 | n/a | |

455 | n/a | """ |

456 | n/a | if isinstance(b, numbers.Rational): |

457 | n/a | if b.denominator == 1: |

458 | n/a | power = b.numerator |

459 | n/a | if power >= 0: |

460 | n/a | return Fraction(a._numerator ** power, |

461 | n/a | a._denominator ** power, |

462 | n/a | _normalize=False) |

463 | n/a | elif a._numerator >= 0: |

464 | n/a | return Fraction(a._denominator ** -power, |

465 | n/a | a._numerator ** -power, |

466 | n/a | _normalize=False) |

467 | n/a | else: |

468 | n/a | return Fraction((-a._denominator) ** -power, |

469 | n/a | (-a._numerator) ** -power, |

470 | n/a | _normalize=False) |

471 | n/a | else: |

472 | n/a | # A fractional power will generally produce an |

473 | n/a | # irrational number. |

474 | n/a | return float(a) ** float(b) |

475 | n/a | else: |

476 | n/a | return float(a) ** b |

477 | n/a | |

478 | n/a | def __rpow__(b, a): |

479 | n/a | """a ** b""" |

480 | n/a | if b._denominator == 1 and b._numerator >= 0: |

481 | n/a | # If a is an int, keep it that way if possible. |

482 | n/a | return a ** b._numerator |

483 | n/a | |

484 | n/a | if isinstance(a, numbers.Rational): |

485 | n/a | return Fraction(a.numerator, a.denominator) ** b |

486 | n/a | |

487 | n/a | if b._denominator == 1: |

488 | n/a | return a ** b._numerator |

489 | n/a | |

490 | n/a | return a ** float(b) |

491 | n/a | |

492 | n/a | def __pos__(a): |

493 | n/a | """+a: Coerces a subclass instance to Fraction""" |

494 | n/a | return Fraction(a._numerator, a._denominator, _normalize=False) |

495 | n/a | |

496 | n/a | def __neg__(a): |

497 | n/a | """-a""" |

498 | n/a | return Fraction(-a._numerator, a._denominator, _normalize=False) |

499 | n/a | |

500 | n/a | def __abs__(a): |

501 | n/a | """abs(a)""" |

502 | n/a | return Fraction(abs(a._numerator), a._denominator, _normalize=False) |

503 | n/a | |

504 | n/a | def __trunc__(a): |

505 | n/a | """trunc(a)""" |

506 | n/a | if a._numerator < 0: |

507 | n/a | return -(-a._numerator // a._denominator) |

508 | n/a | else: |

509 | n/a | return a._numerator // a._denominator |

510 | n/a | |

511 | n/a | def __floor__(a): |

512 | n/a | """Will be math.floor(a) in 3.0.""" |

513 | n/a | return a.numerator // a.denominator |

514 | n/a | |

515 | n/a | def __ceil__(a): |

516 | n/a | """Will be math.ceil(a) in 3.0.""" |

517 | n/a | # The negations cleverly convince floordiv to return the ceiling. |

518 | n/a | return -(-a.numerator // a.denominator) |

519 | n/a | |

520 | n/a | def __round__(self, ndigits=None): |

521 | n/a | """Will be round(self, ndigits) in 3.0. |

522 | n/a | |

523 | n/a | Rounds half toward even. |

524 | n/a | """ |

525 | n/a | if ndigits is None: |

526 | n/a | floor, remainder = divmod(self.numerator, self.denominator) |

527 | n/a | if remainder * 2 < self.denominator: |

528 | n/a | return floor |

529 | n/a | elif remainder * 2 > self.denominator: |

530 | n/a | return floor + 1 |

531 | n/a | # Deal with the half case: |

532 | n/a | elif floor % 2 == 0: |

533 | n/a | return floor |

534 | n/a | else: |

535 | n/a | return floor + 1 |

536 | n/a | shift = 10**abs(ndigits) |

537 | n/a | # See _operator_fallbacks.forward to check that the results of |

538 | n/a | # these operations will always be Fraction and therefore have |

539 | n/a | # round(). |

540 | n/a | if ndigits > 0: |

541 | n/a | return Fraction(round(self * shift), shift) |

542 | n/a | else: |

543 | n/a | return Fraction(round(self / shift) * shift) |

544 | n/a | |

545 | n/a | def __hash__(self): |

546 | n/a | """hash(self)""" |

547 | n/a | |

548 | n/a | # XXX since this method is expensive, consider caching the result |

549 | n/a | |

550 | n/a | # In order to make sure that the hash of a Fraction agrees |

551 | n/a | # with the hash of a numerically equal integer, float or |

552 | n/a | # Decimal instance, we follow the rules for numeric hashes |

553 | n/a | # outlined in the documentation. (See library docs, 'Built-in |

554 | n/a | # Types'). |

555 | n/a | |

556 | n/a | # dinv is the inverse of self._denominator modulo the prime |

557 | n/a | # _PyHASH_MODULUS, or 0 if self._denominator is divisible by |

558 | n/a | # _PyHASH_MODULUS. |

559 | n/a | dinv = pow(self._denominator, _PyHASH_MODULUS - 2, _PyHASH_MODULUS) |

560 | n/a | if not dinv: |

561 | n/a | hash_ = _PyHASH_INF |

562 | n/a | else: |

563 | n/a | hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS |

564 | n/a | result = hash_ if self >= 0 else -hash_ |

565 | n/a | return -2 if result == -1 else result |

566 | n/a | |

567 | n/a | def __eq__(a, b): |

568 | n/a | """a == b""" |

569 | n/a | if type(b) is int: |

570 | n/a | return a._numerator == b and a._denominator == 1 |

571 | n/a | if isinstance(b, numbers.Rational): |

572 | n/a | return (a._numerator == b.numerator and |

573 | n/a | a._denominator == b.denominator) |

574 | n/a | if isinstance(b, numbers.Complex) and b.imag == 0: |

575 | n/a | b = b.real |

576 | n/a | if isinstance(b, float): |

577 | n/a | if math.isnan(b) or math.isinf(b): |

578 | n/a | # comparisons with an infinity or nan should behave in |

579 | n/a | # the same way for any finite a, so treat a as zero. |

580 | n/a | return 0.0 == b |

581 | n/a | else: |

582 | n/a | return a == a.from_float(b) |

583 | n/a | else: |

584 | n/a | # Since a doesn't know how to compare with b, let's give b |

585 | n/a | # a chance to compare itself with a. |

586 | n/a | return NotImplemented |

587 | n/a | |

588 | n/a | def _richcmp(self, other, op): |

589 | n/a | """Helper for comparison operators, for internal use only. |

590 | n/a | |

591 | n/a | Implement comparison between a Rational instance `self`, and |

592 | n/a | either another Rational instance or a float `other`. If |

593 | n/a | `other` is not a Rational instance or a float, return |

594 | n/a | NotImplemented. `op` should be one of the six standard |

595 | n/a | comparison operators. |

596 | n/a | |

597 | n/a | """ |

598 | n/a | # convert other to a Rational instance where reasonable. |

599 | n/a | if isinstance(other, numbers.Rational): |

600 | n/a | return op(self._numerator * other.denominator, |

601 | n/a | self._denominator * other.numerator) |

602 | n/a | if isinstance(other, float): |

603 | n/a | if math.isnan(other) or math.isinf(other): |

604 | n/a | return op(0.0, other) |

605 | n/a | else: |

606 | n/a | return op(self, self.from_float(other)) |

607 | n/a | else: |

608 | n/a | return NotImplemented |

609 | n/a | |

610 | n/a | def __lt__(a, b): |

611 | n/a | """a < b""" |

612 | n/a | return a._richcmp(b, operator.lt) |

613 | n/a | |

614 | n/a | def __gt__(a, b): |

615 | n/a | """a > b""" |

616 | n/a | return a._richcmp(b, operator.gt) |

617 | n/a | |

618 | n/a | def __le__(a, b): |

619 | n/a | """a <= b""" |

620 | n/a | return a._richcmp(b, operator.le) |

621 | n/a | |

622 | n/a | def __ge__(a, b): |

623 | n/a | """a >= b""" |

624 | n/a | return a._richcmp(b, operator.ge) |

625 | n/a | |

626 | n/a | def __bool__(a): |

627 | n/a | """a != 0""" |

628 | n/a | return a._numerator != 0 |

629 | n/a | |

630 | n/a | # support for pickling, copy, and deepcopy |

631 | n/a | |

632 | n/a | def __reduce__(self): |

633 | n/a | return (self.__class__, (str(self),)) |

634 | n/a | |

635 | n/a | def __copy__(self): |

636 | n/a | if type(self) == Fraction: |

637 | n/a | return self # I'm immutable; therefore I am my own clone |

638 | n/a | return self.__class__(self._numerator, self._denominator) |

639 | n/a | |

640 | n/a | def __deepcopy__(self, memo): |

641 | n/a | if type(self) == Fraction: |

642 | n/a | return self # My components are also immutable |

643 | n/a | return self.__class__(self._numerator, self._denominator) |