# Python code coverage for Lib/_pydecimal.py

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

1 | n/a | # Copyright (c) 2004 Python Software Foundation. |

2 | n/a | # All rights reserved. |

3 | n/a | |

4 | n/a | # Written by Eric Price <eprice at tjhsst.edu> |

5 | n/a | # and Facundo Batista <facundo at taniquetil.com.ar> |

6 | n/a | # and Raymond Hettinger <python at rcn.com> |

7 | n/a | # and Aahz <aahz at pobox.com> |

8 | n/a | # and Tim Peters |

9 | n/a | |

10 | n/a | # This module should be kept in sync with the latest updates of the |

11 | n/a | # IBM specification as it evolves. Those updates will be treated |

12 | n/a | # as bug fixes (deviation from the spec is a compatibility, usability |

13 | n/a | # bug) and will be backported. At this point the spec is stabilizing |

14 | n/a | # and the updates are becoming fewer, smaller, and less significant. |

15 | n/a | |

16 | n/a | """ |

17 | n/a | This is an implementation of decimal floating point arithmetic based on |

18 | n/a | the General Decimal Arithmetic Specification: |

19 | n/a | |

20 | n/a | http://speleotrove.com/decimal/decarith.html |

21 | n/a | |

22 | n/a | and IEEE standard 854-1987: |

23 | n/a | |

24 | n/a | http://en.wikipedia.org/wiki/IEEE_854-1987 |

25 | n/a | |

26 | n/a | Decimal floating point has finite precision with arbitrarily large bounds. |

27 | n/a | |

28 | n/a | The purpose of this module is to support arithmetic using familiar |

29 | n/a | "schoolhouse" rules and to avoid some of the tricky representation |

30 | n/a | issues associated with binary floating point. The package is especially |

31 | n/a | useful for financial applications or for contexts where users have |

32 | n/a | expectations that are at odds with binary floating point (for instance, |

33 | n/a | in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead |

34 | n/a | of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected |

35 | n/a | Decimal('0.00')). |

36 | n/a | |

37 | n/a | Here are some examples of using the decimal module: |

38 | n/a | |

39 | n/a | >>> from decimal import * |

40 | n/a | >>> setcontext(ExtendedContext) |

41 | n/a | >>> Decimal(0) |

42 | n/a | Decimal('0') |

43 | n/a | >>> Decimal('1') |

44 | n/a | Decimal('1') |

45 | n/a | >>> Decimal('-.0123') |

46 | n/a | Decimal('-0.0123') |

47 | n/a | >>> Decimal(123456) |

48 | n/a | Decimal('123456') |

49 | n/a | >>> Decimal('123.45e12345678') |

50 | n/a | Decimal('1.2345E+12345680') |

51 | n/a | >>> Decimal('1.33') + Decimal('1.27') |

52 | n/a | Decimal('2.60') |

53 | n/a | >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41') |

54 | n/a | Decimal('-2.20') |

55 | n/a | >>> dig = Decimal(1) |

56 | n/a | >>> print(dig / Decimal(3)) |

57 | n/a | 0.333333333 |

58 | n/a | >>> getcontext().prec = 18 |

59 | n/a | >>> print(dig / Decimal(3)) |

60 | n/a | 0.333333333333333333 |

61 | n/a | >>> print(dig.sqrt()) |

62 | n/a | 1 |

63 | n/a | >>> print(Decimal(3).sqrt()) |

64 | n/a | 1.73205080756887729 |

65 | n/a | >>> print(Decimal(3) ** 123) |

66 | n/a | 4.85192780976896427E+58 |

67 | n/a | >>> inf = Decimal(1) / Decimal(0) |

68 | n/a | >>> print(inf) |

69 | n/a | Infinity |

70 | n/a | >>> neginf = Decimal(-1) / Decimal(0) |

71 | n/a | >>> print(neginf) |

72 | n/a | -Infinity |

73 | n/a | >>> print(neginf + inf) |

74 | n/a | NaN |

75 | n/a | >>> print(neginf * inf) |

76 | n/a | -Infinity |

77 | n/a | >>> print(dig / 0) |

78 | n/a | Infinity |

79 | n/a | >>> getcontext().traps[DivisionByZero] = 1 |

80 | n/a | >>> print(dig / 0) |

81 | n/a | Traceback (most recent call last): |

82 | n/a | ... |

83 | n/a | ... |

84 | n/a | ... |

85 | n/a | decimal.DivisionByZero: x / 0 |

86 | n/a | >>> c = Context() |

87 | n/a | >>> c.traps[InvalidOperation] = 0 |

88 | n/a | >>> print(c.flags[InvalidOperation]) |

89 | n/a | 0 |

90 | n/a | >>> c.divide(Decimal(0), Decimal(0)) |

91 | n/a | Decimal('NaN') |

92 | n/a | >>> c.traps[InvalidOperation] = 1 |

93 | n/a | >>> print(c.flags[InvalidOperation]) |

94 | n/a | 1 |

95 | n/a | >>> c.flags[InvalidOperation] = 0 |

96 | n/a | >>> print(c.flags[InvalidOperation]) |

97 | n/a | 0 |

98 | n/a | >>> print(c.divide(Decimal(0), Decimal(0))) |

99 | n/a | Traceback (most recent call last): |

100 | n/a | ... |

101 | n/a | ... |

102 | n/a | ... |

103 | n/a | decimal.InvalidOperation: 0 / 0 |

104 | n/a | >>> print(c.flags[InvalidOperation]) |

105 | n/a | 1 |

106 | n/a | >>> c.flags[InvalidOperation] = 0 |

107 | n/a | >>> c.traps[InvalidOperation] = 0 |

108 | n/a | >>> print(c.divide(Decimal(0), Decimal(0))) |

109 | n/a | NaN |

110 | n/a | >>> print(c.flags[InvalidOperation]) |

111 | n/a | 1 |

112 | n/a | >>> |

113 | n/a | """ |

114 | n/a | |

115 | n/a | __all__ = [ |

116 | n/a | # Two major classes |

117 | n/a | 'Decimal', 'Context', |

118 | n/a | |

119 | n/a | # Named tuple representation |

120 | n/a | 'DecimalTuple', |

121 | n/a | |

122 | n/a | # Contexts |

123 | n/a | 'DefaultContext', 'BasicContext', 'ExtendedContext', |

124 | n/a | |

125 | n/a | # Exceptions |

126 | n/a | 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero', |

127 | n/a | 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow', |

128 | n/a | 'FloatOperation', |

129 | n/a | |

130 | n/a | # Exceptional conditions that trigger InvalidOperation |

131 | n/a | 'DivisionImpossible', 'InvalidContext', 'ConversionSyntax', 'DivisionUndefined', |

132 | n/a | |

133 | n/a | # Constants for use in setting up contexts |

134 | n/a | 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING', |

135 | n/a | 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP', |

136 | n/a | |

137 | n/a | # Functions for manipulating contexts |

138 | n/a | 'setcontext', 'getcontext', 'localcontext', |

139 | n/a | |

140 | n/a | # Limits for the C version for compatibility |

141 | n/a | 'MAX_PREC', 'MAX_EMAX', 'MIN_EMIN', 'MIN_ETINY', |

142 | n/a | |

143 | n/a | # C version: compile time choice that enables the thread local context |

144 | n/a | 'HAVE_THREADS' |

145 | n/a | ] |

146 | n/a | |

147 | n/a | __xname__ = __name__ # sys.modules lookup (--without-threads) |

148 | n/a | __name__ = 'decimal' # For pickling |

149 | n/a | __version__ = '1.70' # Highest version of the spec this complies with |

150 | n/a | # See http://speleotrove.com/decimal/ |

151 | n/a | __libmpdec_version__ = "2.4.2" # compatible libmpdec version |

152 | n/a | |

153 | n/a | import math as _math |

154 | n/a | import numbers as _numbers |

155 | n/a | import sys |

156 | n/a | |

157 | n/a | try: |

158 | n/a | from collections import namedtuple as _namedtuple |

159 | n/a | DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent') |

160 | n/a | except ImportError: |

161 | n/a | DecimalTuple = lambda *args: args |

162 | n/a | |

163 | n/a | # Rounding |

164 | n/a | ROUND_DOWN = 'ROUND_DOWN' |

165 | n/a | ROUND_HALF_UP = 'ROUND_HALF_UP' |

166 | n/a | ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' |

167 | n/a | ROUND_CEILING = 'ROUND_CEILING' |

168 | n/a | ROUND_FLOOR = 'ROUND_FLOOR' |

169 | n/a | ROUND_UP = 'ROUND_UP' |

170 | n/a | ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' |

171 | n/a | ROUND_05UP = 'ROUND_05UP' |

172 | n/a | |

173 | n/a | # Compatibility with the C version |

174 | n/a | HAVE_THREADS = True |

175 | n/a | if sys.maxsize == 2**63-1: |

176 | n/a | MAX_PREC = 999999999999999999 |

177 | n/a | MAX_EMAX = 999999999999999999 |

178 | n/a | MIN_EMIN = -999999999999999999 |

179 | n/a | else: |

180 | n/a | MAX_PREC = 425000000 |

181 | n/a | MAX_EMAX = 425000000 |

182 | n/a | MIN_EMIN = -425000000 |

183 | n/a | |

184 | n/a | MIN_ETINY = MIN_EMIN - (MAX_PREC-1) |

185 | n/a | |

186 | n/a | # Errors |

187 | n/a | |

188 | n/a | class DecimalException(ArithmeticError): |

189 | n/a | """Base exception class. |

190 | n/a | |

191 | n/a | Used exceptions derive from this. |

192 | n/a | If an exception derives from another exception besides this (such as |

193 | n/a | Underflow (Inexact, Rounded, Subnormal) that indicates that it is only |

194 | n/a | called if the others are present. This isn't actually used for |

195 | n/a | anything, though. |

196 | n/a | |

197 | n/a | handle -- Called when context._raise_error is called and the |

198 | n/a | trap_enabler is not set. First argument is self, second is the |

199 | n/a | context. More arguments can be given, those being after |

200 | n/a | the explanation in _raise_error (For example, |

201 | n/a | context._raise_error(NewError, '(-x)!', self._sign) would |

202 | n/a | call NewError().handle(context, self._sign).) |

203 | n/a | |

204 | n/a | To define a new exception, it should be sufficient to have it derive |

205 | n/a | from DecimalException. |

206 | n/a | """ |

207 | n/a | def handle(self, context, *args): |

208 | n/a | pass |

209 | n/a | |

210 | n/a | |

211 | n/a | class Clamped(DecimalException): |

212 | n/a | """Exponent of a 0 changed to fit bounds. |

213 | n/a | |

214 | n/a | This occurs and signals clamped if the exponent of a result has been |

215 | n/a | altered in order to fit the constraints of a specific concrete |

216 | n/a | representation. This may occur when the exponent of a zero result would |

217 | n/a | be outside the bounds of a representation, or when a large normal |

218 | n/a | number would have an encoded exponent that cannot be represented. In |

219 | n/a | this latter case, the exponent is reduced to fit and the corresponding |

220 | n/a | number of zero digits are appended to the coefficient ("fold-down"). |

221 | n/a | """ |

222 | n/a | |

223 | n/a | class InvalidOperation(DecimalException): |

224 | n/a | """An invalid operation was performed. |

225 | n/a | |

226 | n/a | Various bad things cause this: |

227 | n/a | |

228 | n/a | Something creates a signaling NaN |

229 | n/a | -INF + INF |

230 | n/a | 0 * (+-)INF |

231 | n/a | (+-)INF / (+-)INF |

232 | n/a | x % 0 |

233 | n/a | (+-)INF % x |

234 | n/a | x._rescale( non-integer ) |

235 | n/a | sqrt(-x) , x > 0 |

236 | n/a | 0 ** 0 |

237 | n/a | x ** (non-integer) |

238 | n/a | x ** (+-)INF |

239 | n/a | An operand is invalid |

240 | n/a | |

241 | n/a | The result of the operation after these is a quiet positive NaN, |

242 | n/a | except when the cause is a signaling NaN, in which case the result is |

243 | n/a | also a quiet NaN, but with the original sign, and an optional |

244 | n/a | diagnostic information. |

245 | n/a | """ |

246 | n/a | def handle(self, context, *args): |

247 | n/a | if args: |

248 | n/a | ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True) |

249 | n/a | return ans._fix_nan(context) |

250 | n/a | return _NaN |

251 | n/a | |

252 | n/a | class ConversionSyntax(InvalidOperation): |

253 | n/a | """Trying to convert badly formed string. |

254 | n/a | |

255 | n/a | This occurs and signals invalid-operation if a string is being |

256 | n/a | converted to a number and it does not conform to the numeric string |

257 | n/a | syntax. The result is [0,qNaN]. |

258 | n/a | """ |

259 | n/a | def handle(self, context, *args): |

260 | n/a | return _NaN |

261 | n/a | |

262 | n/a | class DivisionByZero(DecimalException, ZeroDivisionError): |

263 | n/a | """Division by 0. |

264 | n/a | |

265 | n/a | This occurs and signals division-by-zero if division of a finite number |

266 | n/a | by zero was attempted (during a divide-integer or divide operation, or a |

267 | n/a | power operation with negative right-hand operand), and the dividend was |

268 | n/a | not zero. |

269 | n/a | |

270 | n/a | The result of the operation is [sign,inf], where sign is the exclusive |

271 | n/a | or of the signs of the operands for divide, or is 1 for an odd power of |

272 | n/a | -0, for power. |

273 | n/a | """ |

274 | n/a | |

275 | n/a | def handle(self, context, sign, *args): |

276 | n/a | return _SignedInfinity[sign] |

277 | n/a | |

278 | n/a | class DivisionImpossible(InvalidOperation): |

279 | n/a | """Cannot perform the division adequately. |

280 | n/a | |

281 | n/a | This occurs and signals invalid-operation if the integer result of a |

282 | n/a | divide-integer or remainder operation had too many digits (would be |

283 | n/a | longer than precision). The result is [0,qNaN]. |

284 | n/a | """ |

285 | n/a | |

286 | n/a | def handle(self, context, *args): |

287 | n/a | return _NaN |

288 | n/a | |

289 | n/a | class DivisionUndefined(InvalidOperation, ZeroDivisionError): |

290 | n/a | """Undefined result of division. |

291 | n/a | |

292 | n/a | This occurs and signals invalid-operation if division by zero was |

293 | n/a | attempted (during a divide-integer, divide, or remainder operation), and |

294 | n/a | the dividend is also zero. The result is [0,qNaN]. |

295 | n/a | """ |

296 | n/a | |

297 | n/a | def handle(self, context, *args): |

298 | n/a | return _NaN |

299 | n/a | |

300 | n/a | class Inexact(DecimalException): |

301 | n/a | """Had to round, losing information. |

302 | n/a | |

303 | n/a | This occurs and signals inexact whenever the result of an operation is |

304 | n/a | not exact (that is, it needed to be rounded and any discarded digits |

305 | n/a | were non-zero), or if an overflow or underflow condition occurs. The |

306 | n/a | result in all cases is unchanged. |

307 | n/a | |

308 | n/a | The inexact signal may be tested (or trapped) to determine if a given |

309 | n/a | operation (or sequence of operations) was inexact. |

310 | n/a | """ |

311 | n/a | |

312 | n/a | class InvalidContext(InvalidOperation): |

313 | n/a | """Invalid context. Unknown rounding, for example. |

314 | n/a | |

315 | n/a | This occurs and signals invalid-operation if an invalid context was |

316 | n/a | detected during an operation. This can occur if contexts are not checked |

317 | n/a | on creation and either the precision exceeds the capability of the |

318 | n/a | underlying concrete representation or an unknown or unsupported rounding |

319 | n/a | was specified. These aspects of the context need only be checked when |

320 | n/a | the values are required to be used. The result is [0,qNaN]. |

321 | n/a | """ |

322 | n/a | |

323 | n/a | def handle(self, context, *args): |

324 | n/a | return _NaN |

325 | n/a | |

326 | n/a | class Rounded(DecimalException): |

327 | n/a | """Number got rounded (not necessarily changed during rounding). |

328 | n/a | |

329 | n/a | This occurs and signals rounded whenever the result of an operation is |

330 | n/a | rounded (that is, some zero or non-zero digits were discarded from the |

331 | n/a | coefficient), or if an overflow or underflow condition occurs. The |

332 | n/a | result in all cases is unchanged. |

333 | n/a | |

334 | n/a | The rounded signal may be tested (or trapped) to determine if a given |

335 | n/a | operation (or sequence of operations) caused a loss of precision. |

336 | n/a | """ |

337 | n/a | |

338 | n/a | class Subnormal(DecimalException): |

339 | n/a | """Exponent < Emin before rounding. |

340 | n/a | |

341 | n/a | This occurs and signals subnormal whenever the result of a conversion or |

342 | n/a | operation is subnormal (that is, its adjusted exponent is less than |

343 | n/a | Emin, before any rounding). The result in all cases is unchanged. |

344 | n/a | |

345 | n/a | The subnormal signal may be tested (or trapped) to determine if a given |

346 | n/a | or operation (or sequence of operations) yielded a subnormal result. |

347 | n/a | """ |

348 | n/a | |

349 | n/a | class Overflow(Inexact, Rounded): |

350 | n/a | """Numerical overflow. |

351 | n/a | |

352 | n/a | This occurs and signals overflow if the adjusted exponent of a result |

353 | n/a | (from a conversion or from an operation that is not an attempt to divide |

354 | n/a | by zero), after rounding, would be greater than the largest value that |

355 | n/a | can be handled by the implementation (the value Emax). |

356 | n/a | |

357 | n/a | The result depends on the rounding mode: |

358 | n/a | |

359 | n/a | For round-half-up and round-half-even (and for round-half-down and |

360 | n/a | round-up, if implemented), the result of the operation is [sign,inf], |

361 | n/a | where sign is the sign of the intermediate result. For round-down, the |

362 | n/a | result is the largest finite number that can be represented in the |

363 | n/a | current precision, with the sign of the intermediate result. For |

364 | n/a | round-ceiling, the result is the same as for round-down if the sign of |

365 | n/a | the intermediate result is 1, or is [0,inf] otherwise. For round-floor, |

366 | n/a | the result is the same as for round-down if the sign of the intermediate |

367 | n/a | result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded |

368 | n/a | will also be raised. |

369 | n/a | """ |

370 | n/a | |

371 | n/a | def handle(self, context, sign, *args): |

372 | n/a | if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, |

373 | n/a | ROUND_HALF_DOWN, ROUND_UP): |

374 | n/a | return _SignedInfinity[sign] |

375 | n/a | if sign == 0: |

376 | n/a | if context.rounding == ROUND_CEILING: |

377 | n/a | return _SignedInfinity[sign] |

378 | n/a | return _dec_from_triple(sign, '9'*context.prec, |

379 | n/a | context.Emax-context.prec+1) |

380 | n/a | if sign == 1: |

381 | n/a | if context.rounding == ROUND_FLOOR: |

382 | n/a | return _SignedInfinity[sign] |

383 | n/a | return _dec_from_triple(sign, '9'*context.prec, |

384 | n/a | context.Emax-context.prec+1) |

385 | n/a | |

386 | n/a | |

387 | n/a | class Underflow(Inexact, Rounded, Subnormal): |

388 | n/a | """Numerical underflow with result rounded to 0. |

389 | n/a | |

390 | n/a | This occurs and signals underflow if a result is inexact and the |

391 | n/a | adjusted exponent of the result would be smaller (more negative) than |

392 | n/a | the smallest value that can be handled by the implementation (the value |

393 | n/a | Emin). That is, the result is both inexact and subnormal. |

394 | n/a | |

395 | n/a | The result after an underflow will be a subnormal number rounded, if |

396 | n/a | necessary, so that its exponent is not less than Etiny. This may result |

397 | n/a | in 0 with the sign of the intermediate result and an exponent of Etiny. |

398 | n/a | |

399 | n/a | In all cases, Inexact, Rounded, and Subnormal will also be raised. |

400 | n/a | """ |

401 | n/a | |

402 | n/a | class FloatOperation(DecimalException, TypeError): |

403 | n/a | """Enable stricter semantics for mixing floats and Decimals. |

404 | n/a | |

405 | n/a | If the signal is not trapped (default), mixing floats and Decimals is |

406 | n/a | permitted in the Decimal() constructor, context.create_decimal() and |

407 | n/a | all comparison operators. Both conversion and comparisons are exact. |

408 | n/a | Any occurrence of a mixed operation is silently recorded by setting |

409 | n/a | FloatOperation in the context flags. Explicit conversions with |

410 | n/a | Decimal.from_float() or context.create_decimal_from_float() do not |

411 | n/a | set the flag. |

412 | n/a | |

413 | n/a | Otherwise (the signal is trapped), only equality comparisons and explicit |

414 | n/a | conversions are silent. All other mixed operations raise FloatOperation. |

415 | n/a | """ |

416 | n/a | |

417 | n/a | # List of public traps and flags |

418 | n/a | _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, |

419 | n/a | Underflow, InvalidOperation, Subnormal, FloatOperation] |

420 | n/a | |

421 | n/a | # Map conditions (per the spec) to signals |

422 | n/a | _condition_map = {ConversionSyntax:InvalidOperation, |

423 | n/a | DivisionImpossible:InvalidOperation, |

424 | n/a | DivisionUndefined:InvalidOperation, |

425 | n/a | InvalidContext:InvalidOperation} |

426 | n/a | |

427 | n/a | # Valid rounding modes |

428 | n/a | _rounding_modes = (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_CEILING, |

429 | n/a | ROUND_FLOOR, ROUND_UP, ROUND_HALF_DOWN, ROUND_05UP) |

430 | n/a | |

431 | n/a | ##### Context Functions ################################################## |

432 | n/a | |

433 | n/a | # The getcontext() and setcontext() function manage access to a thread-local |

434 | n/a | # current context. Py2.4 offers direct support for thread locals. If that |

435 | n/a | # is not available, use threading.current_thread() which is slower but will |

436 | n/a | # work for older Pythons. If threads are not part of the build, create a |

437 | n/a | # mock threading object with threading.local() returning the module namespace. |

438 | n/a | |

439 | n/a | try: |

440 | n/a | import threading |

441 | n/a | except ImportError: |

442 | n/a | # Python was compiled without threads; create a mock object instead |

443 | n/a | class MockThreading(object): |

444 | n/a | def local(self, sys=sys): |

445 | n/a | return sys.modules[__xname__] |

446 | n/a | threading = MockThreading() |

447 | n/a | del MockThreading |

448 | n/a | |

449 | n/a | try: |

450 | n/a | threading.local |

451 | n/a | |

452 | n/a | except AttributeError: |

453 | n/a | |

454 | n/a | # To fix reloading, force it to create a new context |

455 | n/a | # Old contexts have different exceptions in their dicts, making problems. |

456 | n/a | if hasattr(threading.current_thread(), '__decimal_context__'): |

457 | n/a | del threading.current_thread().__decimal_context__ |

458 | n/a | |

459 | n/a | def setcontext(context): |

460 | n/a | """Set this thread's context to context.""" |

461 | n/a | if context in (DefaultContext, BasicContext, ExtendedContext): |

462 | n/a | context = context.copy() |

463 | n/a | context.clear_flags() |

464 | n/a | threading.current_thread().__decimal_context__ = context |

465 | n/a | |

466 | n/a | def getcontext(): |

467 | n/a | """Returns this thread's context. |

468 | n/a | |

469 | n/a | If this thread does not yet have a context, returns |

470 | n/a | a new context and sets this thread's context. |

471 | n/a | New contexts are copies of DefaultContext. |

472 | n/a | """ |

473 | n/a | try: |

474 | n/a | return threading.current_thread().__decimal_context__ |

475 | n/a | except AttributeError: |

476 | n/a | context = Context() |

477 | n/a | threading.current_thread().__decimal_context__ = context |

478 | n/a | return context |

479 | n/a | |

480 | n/a | else: |

481 | n/a | |

482 | n/a | local = threading.local() |

483 | n/a | if hasattr(local, '__decimal_context__'): |

484 | n/a | del local.__decimal_context__ |

485 | n/a | |

486 | n/a | def getcontext(_local=local): |

487 | n/a | """Returns this thread's context. |

488 | n/a | |

489 | n/a | If this thread does not yet have a context, returns |

490 | n/a | a new context and sets this thread's context. |

491 | n/a | New contexts are copies of DefaultContext. |

492 | n/a | """ |

493 | n/a | try: |

494 | n/a | return _local.__decimal_context__ |

495 | n/a | except AttributeError: |

496 | n/a | context = Context() |

497 | n/a | _local.__decimal_context__ = context |

498 | n/a | return context |

499 | n/a | |

500 | n/a | def setcontext(context, _local=local): |

501 | n/a | """Set this thread's context to context.""" |

502 | n/a | if context in (DefaultContext, BasicContext, ExtendedContext): |

503 | n/a | context = context.copy() |

504 | n/a | context.clear_flags() |

505 | n/a | _local.__decimal_context__ = context |

506 | n/a | |

507 | n/a | del threading, local # Don't contaminate the namespace |

508 | n/a | |

509 | n/a | def localcontext(ctx=None): |

510 | n/a | """Return a context manager for a copy of the supplied context |

511 | n/a | |

512 | n/a | Uses a copy of the current context if no context is specified |

513 | n/a | The returned context manager creates a local decimal context |

514 | n/a | in a with statement: |

515 | n/a | def sin(x): |

516 | n/a | with localcontext() as ctx: |

517 | n/a | ctx.prec += 2 |

518 | n/a | # Rest of sin calculation algorithm |

519 | n/a | # uses a precision 2 greater than normal |

520 | n/a | return +s # Convert result to normal precision |

521 | n/a | |

522 | n/a | def sin(x): |

523 | n/a | with localcontext(ExtendedContext): |

524 | n/a | # Rest of sin calculation algorithm |

525 | n/a | # uses the Extended Context from the |

526 | n/a | # General Decimal Arithmetic Specification |

527 | n/a | return +s # Convert result to normal context |

528 | n/a | |

529 | n/a | >>> setcontext(DefaultContext) |

530 | n/a | >>> print(getcontext().prec) |

531 | n/a | 28 |

532 | n/a | >>> with localcontext(): |

533 | n/a | ... ctx = getcontext() |

534 | n/a | ... ctx.prec += 2 |

535 | n/a | ... print(ctx.prec) |

536 | n/a | ... |

537 | n/a | 30 |

538 | n/a | >>> with localcontext(ExtendedContext): |

539 | n/a | ... print(getcontext().prec) |

540 | n/a | ... |

541 | n/a | 9 |

542 | n/a | >>> print(getcontext().prec) |

543 | n/a | 28 |

544 | n/a | """ |

545 | n/a | if ctx is None: ctx = getcontext() |

546 | n/a | return _ContextManager(ctx) |

547 | n/a | |

548 | n/a | |

549 | n/a | ##### Decimal class ####################################################### |

550 | n/a | |

551 | n/a | # Do not subclass Decimal from numbers.Real and do not register it as such |

552 | n/a | # (because Decimals are not interoperable with floats). See the notes in |

553 | n/a | # numbers.py for more detail. |

554 | n/a | |

555 | n/a | class Decimal(object): |

556 | n/a | """Floating point class for decimal arithmetic.""" |

557 | n/a | |

558 | n/a | __slots__ = ('_exp','_int','_sign', '_is_special') |

559 | n/a | # Generally, the value of the Decimal instance is given by |

560 | n/a | # (-1)**_sign * _int * 10**_exp |

561 | n/a | # Special values are signified by _is_special == True |

562 | n/a | |

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

564 | n/a | def __new__(cls, value="0", context=None): |

565 | n/a | """Create a decimal point instance. |

566 | n/a | |

567 | n/a | >>> Decimal('3.14') # string input |

568 | n/a | Decimal('3.14') |

569 | n/a | >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) |

570 | n/a | Decimal('3.14') |

571 | n/a | >>> Decimal(314) # int |

572 | n/a | Decimal('314') |

573 | n/a | >>> Decimal(Decimal(314)) # another decimal instance |

574 | n/a | Decimal('314') |

575 | n/a | >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay |

576 | n/a | Decimal('3.14') |

577 | n/a | """ |

578 | n/a | |

579 | n/a | # Note that the coefficient, self._int, is actually stored as |

580 | n/a | # a string rather than as a tuple of digits. This speeds up |

581 | n/a | # the "digits to integer" and "integer to digits" conversions |

582 | n/a | # that are used in almost every arithmetic operation on |

583 | n/a | # Decimals. This is an internal detail: the as_tuple function |

584 | n/a | # and the Decimal constructor still deal with tuples of |

585 | n/a | # digits. |

586 | n/a | |

587 | n/a | self = object.__new__(cls) |

588 | n/a | |

589 | n/a | # From a string |

590 | n/a | # REs insist on real strings, so we can too. |

591 | n/a | if isinstance(value, str): |

592 | n/a | m = _parser(value.strip().replace("_", "")) |

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

594 | n/a | if context is None: |

595 | n/a | context = getcontext() |

596 | n/a | return context._raise_error(ConversionSyntax, |

597 | n/a | "Invalid literal for Decimal: %r" % value) |

598 | n/a | |

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

600 | n/a | self._sign = 1 |

601 | n/a | else: |

602 | n/a | self._sign = 0 |

603 | n/a | intpart = m.group('int') |

604 | n/a | if intpart is not None: |

605 | n/a | # finite number |

606 | n/a | fracpart = m.group('frac') or '' |

607 | n/a | exp = int(m.group('exp') or '0') |

608 | n/a | self._int = str(int(intpart+fracpart)) |

609 | n/a | self._exp = exp - len(fracpart) |

610 | n/a | self._is_special = False |

611 | n/a | else: |

612 | n/a | diag = m.group('diag') |

613 | n/a | if diag is not None: |

614 | n/a | # NaN |

615 | n/a | self._int = str(int(diag or '0')).lstrip('0') |

616 | n/a | if m.group('signal'): |

617 | n/a | self._exp = 'N' |

618 | n/a | else: |

619 | n/a | self._exp = 'n' |

620 | n/a | else: |

621 | n/a | # infinity |

622 | n/a | self._int = '0' |

623 | n/a | self._exp = 'F' |

624 | n/a | self._is_special = True |

625 | n/a | return self |

626 | n/a | |

627 | n/a | # From an integer |

628 | n/a | if isinstance(value, int): |

629 | n/a | if value >= 0: |

630 | n/a | self._sign = 0 |

631 | n/a | else: |

632 | n/a | self._sign = 1 |

633 | n/a | self._exp = 0 |

634 | n/a | self._int = str(abs(value)) |

635 | n/a | self._is_special = False |

636 | n/a | return self |

637 | n/a | |

638 | n/a | # From another decimal |

639 | n/a | if isinstance(value, Decimal): |

640 | n/a | self._exp = value._exp |

641 | n/a | self._sign = value._sign |

642 | n/a | self._int = value._int |

643 | n/a | self._is_special = value._is_special |

644 | n/a | return self |

645 | n/a | |

646 | n/a | # From an internal working value |

647 | n/a | if isinstance(value, _WorkRep): |

648 | n/a | self._sign = value.sign |

649 | n/a | self._int = str(value.int) |

650 | n/a | self._exp = int(value.exp) |

651 | n/a | self._is_special = False |

652 | n/a | return self |

653 | n/a | |

654 | n/a | # tuple/list conversion (possibly from as_tuple()) |

655 | n/a | if isinstance(value, (list,tuple)): |

656 | n/a | if len(value) != 3: |

657 | n/a | raise ValueError('Invalid tuple size in creation of Decimal ' |

658 | n/a | 'from list or tuple. The list or tuple ' |

659 | n/a | 'should have exactly three elements.') |

660 | n/a | # process sign. The isinstance test rejects floats |

661 | n/a | if not (isinstance(value[0], int) and value[0] in (0,1)): |

662 | n/a | raise ValueError("Invalid sign. The first value in the tuple " |

663 | n/a | "should be an integer; either 0 for a " |

664 | n/a | "positive number or 1 for a negative number.") |

665 | n/a | self._sign = value[0] |

666 | n/a | if value[2] == 'F': |

667 | n/a | # infinity: value[1] is ignored |

668 | n/a | self._int = '0' |

669 | n/a | self._exp = value[2] |

670 | n/a | self._is_special = True |

671 | n/a | else: |

672 | n/a | # process and validate the digits in value[1] |

673 | n/a | digits = [] |

674 | n/a | for digit in value[1]: |

675 | n/a | if isinstance(digit, int) and 0 <= digit <= 9: |

676 | n/a | # skip leading zeros |

677 | n/a | if digits or digit != 0: |

678 | n/a | digits.append(digit) |

679 | n/a | else: |

680 | n/a | raise ValueError("The second value in the tuple must " |

681 | n/a | "be composed of integers in the range " |

682 | n/a | "0 through 9.") |

683 | n/a | if value[2] in ('n', 'N'): |

684 | n/a | # NaN: digits form the diagnostic |

685 | n/a | self._int = ''.join(map(str, digits)) |

686 | n/a | self._exp = value[2] |

687 | n/a | self._is_special = True |

688 | n/a | elif isinstance(value[2], int): |

689 | n/a | # finite number: digits give the coefficient |

690 | n/a | self._int = ''.join(map(str, digits or [0])) |

691 | n/a | self._exp = value[2] |

692 | n/a | self._is_special = False |

693 | n/a | else: |

694 | n/a | raise ValueError("The third value in the tuple must " |

695 | n/a | "be an integer, or one of the " |

696 | n/a | "strings 'F', 'n', 'N'.") |

697 | n/a | return self |

698 | n/a | |

699 | n/a | if isinstance(value, float): |

700 | n/a | if context is None: |

701 | n/a | context = getcontext() |

702 | n/a | context._raise_error(FloatOperation, |

703 | n/a | "strict semantics for mixing floats and Decimals are " |

704 | n/a | "enabled") |

705 | n/a | value = Decimal.from_float(value) |

706 | n/a | self._exp = value._exp |

707 | n/a | self._sign = value._sign |

708 | n/a | self._int = value._int |

709 | n/a | self._is_special = value._is_special |

710 | n/a | return self |

711 | n/a | |

712 | n/a | raise TypeError("Cannot convert %r to Decimal" % value) |

713 | n/a | |

714 | n/a | @classmethod |

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

716 | n/a | """Converts a float to a decimal number, exactly. |

717 | n/a | |

718 | n/a | Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). |

719 | n/a | Since 0.1 is not exactly representable in binary floating point, the |

720 | n/a | value is stored as the nearest representable value which is |

721 | n/a | 0x1.999999999999ap-4. The exact equivalent of the value in decimal |

722 | n/a | is 0.1000000000000000055511151231257827021181583404541015625. |

723 | n/a | |

724 | n/a | >>> Decimal.from_float(0.1) |

725 | n/a | Decimal('0.1000000000000000055511151231257827021181583404541015625') |

726 | n/a | >>> Decimal.from_float(float('nan')) |

727 | n/a | Decimal('NaN') |

728 | n/a | >>> Decimal.from_float(float('inf')) |

729 | n/a | Decimal('Infinity') |

730 | n/a | >>> Decimal.from_float(-float('inf')) |

731 | n/a | Decimal('-Infinity') |

732 | n/a | >>> Decimal.from_float(-0.0) |

733 | n/a | Decimal('-0') |

734 | n/a | |

735 | n/a | """ |

736 | n/a | if isinstance(f, int): # handle integer inputs |

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

738 | n/a | if not isinstance(f, float): |

739 | n/a | raise TypeError("argument must be int or float.") |

740 | n/a | if _math.isinf(f) or _math.isnan(f): |

741 | n/a | return cls(repr(f)) |

742 | n/a | if _math.copysign(1.0, f) == 1.0: |

743 | n/a | sign = 0 |

744 | n/a | else: |

745 | n/a | sign = 1 |

746 | n/a | n, d = abs(f).as_integer_ratio() |

747 | n/a | k = d.bit_length() - 1 |

748 | n/a | result = _dec_from_triple(sign, str(n*5**k), -k) |

749 | n/a | if cls is Decimal: |

750 | n/a | return result |

751 | n/a | else: |

752 | n/a | return cls(result) |

753 | n/a | |

754 | n/a | def _isnan(self): |

755 | n/a | """Returns whether the number is not actually one. |

756 | n/a | |

757 | n/a | 0 if a number |

758 | n/a | 1 if NaN |

759 | n/a | 2 if sNaN |

760 | n/a | """ |

761 | n/a | if self._is_special: |

762 | n/a | exp = self._exp |

763 | n/a | if exp == 'n': |

764 | n/a | return 1 |

765 | n/a | elif exp == 'N': |

766 | n/a | return 2 |

767 | n/a | return 0 |

768 | n/a | |

769 | n/a | def _isinfinity(self): |

770 | n/a | """Returns whether the number is infinite |

771 | n/a | |

772 | n/a | 0 if finite or not a number |

773 | n/a | 1 if +INF |

774 | n/a | -1 if -INF |

775 | n/a | """ |

776 | n/a | if self._exp == 'F': |

777 | n/a | if self._sign: |

778 | n/a | return -1 |

779 | n/a | return 1 |

780 | n/a | return 0 |

781 | n/a | |

782 | n/a | def _check_nans(self, other=None, context=None): |

783 | n/a | """Returns whether the number is not actually one. |

784 | n/a | |

785 | n/a | if self, other are sNaN, signal |

786 | n/a | if self, other are NaN return nan |

787 | n/a | return 0 |

788 | n/a | |

789 | n/a | Done before operations. |

790 | n/a | """ |

791 | n/a | |

792 | n/a | self_is_nan = self._isnan() |

793 | n/a | if other is None: |

794 | n/a | other_is_nan = False |

795 | n/a | else: |

796 | n/a | other_is_nan = other._isnan() |

797 | n/a | |

798 | n/a | if self_is_nan or other_is_nan: |

799 | n/a | if context is None: |

800 | n/a | context = getcontext() |

801 | n/a | |

802 | n/a | if self_is_nan == 2: |

803 | n/a | return context._raise_error(InvalidOperation, 'sNaN', |

804 | n/a | self) |

805 | n/a | if other_is_nan == 2: |

806 | n/a | return context._raise_error(InvalidOperation, 'sNaN', |

807 | n/a | other) |

808 | n/a | if self_is_nan: |

809 | n/a | return self._fix_nan(context) |

810 | n/a | |

811 | n/a | return other._fix_nan(context) |

812 | n/a | return 0 |

813 | n/a | |

814 | n/a | def _compare_check_nans(self, other, context): |

815 | n/a | """Version of _check_nans used for the signaling comparisons |

816 | n/a | compare_signal, __le__, __lt__, __ge__, __gt__. |

817 | n/a | |

818 | n/a | Signal InvalidOperation if either self or other is a (quiet |

819 | n/a | or signaling) NaN. Signaling NaNs take precedence over quiet |

820 | n/a | NaNs. |

821 | n/a | |

822 | n/a | Return 0 if neither operand is a NaN. |

823 | n/a | |

824 | n/a | """ |

825 | n/a | if context is None: |

826 | n/a | context = getcontext() |

827 | n/a | |

828 | n/a | if self._is_special or other._is_special: |

829 | n/a | if self.is_snan(): |

830 | n/a | return context._raise_error(InvalidOperation, |

831 | n/a | 'comparison involving sNaN', |

832 | n/a | self) |

833 | n/a | elif other.is_snan(): |

834 | n/a | return context._raise_error(InvalidOperation, |

835 | n/a | 'comparison involving sNaN', |

836 | n/a | other) |

837 | n/a | elif self.is_qnan(): |

838 | n/a | return context._raise_error(InvalidOperation, |

839 | n/a | 'comparison involving NaN', |

840 | n/a | self) |

841 | n/a | elif other.is_qnan(): |

842 | n/a | return context._raise_error(InvalidOperation, |

843 | n/a | 'comparison involving NaN', |

844 | n/a | other) |

845 | n/a | return 0 |

846 | n/a | |

847 | n/a | def __bool__(self): |

848 | n/a | """Return True if self is nonzero; otherwise return False. |

849 | n/a | |

850 | n/a | NaNs and infinities are considered nonzero. |

851 | n/a | """ |

852 | n/a | return self._is_special or self._int != '0' |

853 | n/a | |

854 | n/a | def _cmp(self, other): |

855 | n/a | """Compare the two non-NaN decimal instances self and other. |

856 | n/a | |

857 | n/a | Returns -1 if self < other, 0 if self == other and 1 |

858 | n/a | if self > other. This routine is for internal use only.""" |

859 | n/a | |

860 | n/a | if self._is_special or other._is_special: |

861 | n/a | self_inf = self._isinfinity() |

862 | n/a | other_inf = other._isinfinity() |

863 | n/a | if self_inf == other_inf: |

864 | n/a | return 0 |

865 | n/a | elif self_inf < other_inf: |

866 | n/a | return -1 |

867 | n/a | else: |

868 | n/a | return 1 |

869 | n/a | |

870 | n/a | # check for zeros; Decimal('0') == Decimal('-0') |

871 | n/a | if not self: |

872 | n/a | if not other: |

873 | n/a | return 0 |

874 | n/a | else: |

875 | n/a | return -((-1)**other._sign) |

876 | n/a | if not other: |

877 | n/a | return (-1)**self._sign |

878 | n/a | |

879 | n/a | # If different signs, neg one is less |

880 | n/a | if other._sign < self._sign: |

881 | n/a | return -1 |

882 | n/a | if self._sign < other._sign: |

883 | n/a | return 1 |

884 | n/a | |

885 | n/a | self_adjusted = self.adjusted() |

886 | n/a | other_adjusted = other.adjusted() |

887 | n/a | if self_adjusted == other_adjusted: |

888 | n/a | self_padded = self._int + '0'*(self._exp - other._exp) |

889 | n/a | other_padded = other._int + '0'*(other._exp - self._exp) |

890 | n/a | if self_padded == other_padded: |

891 | n/a | return 0 |

892 | n/a | elif self_padded < other_padded: |

893 | n/a | return -(-1)**self._sign |

894 | n/a | else: |

895 | n/a | return (-1)**self._sign |

896 | n/a | elif self_adjusted > other_adjusted: |

897 | n/a | return (-1)**self._sign |

898 | n/a | else: # self_adjusted < other_adjusted |

899 | n/a | return -((-1)**self._sign) |

900 | n/a | |

901 | n/a | # Note: The Decimal standard doesn't cover rich comparisons for |

902 | n/a | # Decimals. In particular, the specification is silent on the |

903 | n/a | # subject of what should happen for a comparison involving a NaN. |

904 | n/a | # We take the following approach: |

905 | n/a | # |

906 | n/a | # == comparisons involving a quiet NaN always return False |

907 | n/a | # != comparisons involving a quiet NaN always return True |

908 | n/a | # == or != comparisons involving a signaling NaN signal |

909 | n/a | # InvalidOperation, and return False or True as above if the |

910 | n/a | # InvalidOperation is not trapped. |

911 | n/a | # <, >, <= and >= comparisons involving a (quiet or signaling) |

912 | n/a | # NaN signal InvalidOperation, and return False if the |

913 | n/a | # InvalidOperation is not trapped. |

914 | n/a | # |

915 | n/a | # This behavior is designed to conform as closely as possible to |

916 | n/a | # that specified by IEEE 754. |

917 | n/a | |

918 | n/a | def __eq__(self, other, context=None): |

919 | n/a | self, other = _convert_for_comparison(self, other, equality_op=True) |

920 | n/a | if other is NotImplemented: |

921 | n/a | return other |

922 | n/a | if self._check_nans(other, context): |

923 | n/a | return False |

924 | n/a | return self._cmp(other) == 0 |

925 | n/a | |

926 | n/a | def __lt__(self, other, context=None): |

927 | n/a | self, other = _convert_for_comparison(self, other) |

928 | n/a | if other is NotImplemented: |

929 | n/a | return other |

930 | n/a | ans = self._compare_check_nans(other, context) |

931 | n/a | if ans: |

932 | n/a | return False |

933 | n/a | return self._cmp(other) < 0 |

934 | n/a | |

935 | n/a | def __le__(self, other, context=None): |

936 | n/a | self, other = _convert_for_comparison(self, other) |

937 | n/a | if other is NotImplemented: |

938 | n/a | return other |

939 | n/a | ans = self._compare_check_nans(other, context) |

940 | n/a | if ans: |

941 | n/a | return False |

942 | n/a | return self._cmp(other) <= 0 |

943 | n/a | |

944 | n/a | def __gt__(self, other, context=None): |

945 | n/a | self, other = _convert_for_comparison(self, other) |

946 | n/a | if other is NotImplemented: |

947 | n/a | return other |

948 | n/a | ans = self._compare_check_nans(other, context) |

949 | n/a | if ans: |

950 | n/a | return False |

951 | n/a | return self._cmp(other) > 0 |

952 | n/a | |

953 | n/a | def __ge__(self, other, context=None): |

954 | n/a | self, other = _convert_for_comparison(self, other) |

955 | n/a | if other is NotImplemented: |

956 | n/a | return other |

957 | n/a | ans = self._compare_check_nans(other, context) |

958 | n/a | if ans: |

959 | n/a | return False |

960 | n/a | return self._cmp(other) >= 0 |

961 | n/a | |

962 | n/a | def compare(self, other, context=None): |

963 | n/a | """Compare self to other. Return a decimal value: |

964 | n/a | |

965 | n/a | a or b is a NaN ==> Decimal('NaN') |

966 | n/a | a < b ==> Decimal('-1') |

967 | n/a | a == b ==> Decimal('0') |

968 | n/a | a > b ==> Decimal('1') |

969 | n/a | """ |

970 | n/a | other = _convert_other(other, raiseit=True) |

971 | n/a | |

972 | n/a | # Compare(NaN, NaN) = NaN |

973 | n/a | if (self._is_special or other and other._is_special): |

974 | n/a | ans = self._check_nans(other, context) |

975 | n/a | if ans: |

976 | n/a | return ans |

977 | n/a | |

978 | n/a | return Decimal(self._cmp(other)) |

979 | n/a | |

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

981 | n/a | """x.__hash__() <==> hash(x)""" |

982 | n/a | |

983 | n/a | # In order to make sure that the hash of a Decimal instance |

984 | n/a | # agrees with the hash of a numerically equal integer, float |

985 | n/a | # or Fraction, we follow the rules for numeric hashes outlined |

986 | n/a | # in the documentation. (See library docs, 'Built-in Types'). |

987 | n/a | if self._is_special: |

988 | n/a | if self.is_snan(): |

989 | n/a | raise TypeError('Cannot hash a signaling NaN value.') |

990 | n/a | elif self.is_nan(): |

991 | n/a | return _PyHASH_NAN |

992 | n/a | else: |

993 | n/a | if self._sign: |

994 | n/a | return -_PyHASH_INF |

995 | n/a | else: |

996 | n/a | return _PyHASH_INF |

997 | n/a | |

998 | n/a | if self._exp >= 0: |

999 | n/a | exp_hash = pow(10, self._exp, _PyHASH_MODULUS) |

1000 | n/a | else: |

1001 | n/a | exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS) |

1002 | n/a | hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS |

1003 | n/a | ans = hash_ if self >= 0 else -hash_ |

1004 | n/a | return -2 if ans == -1 else ans |

1005 | n/a | |

1006 | n/a | def as_tuple(self): |

1007 | n/a | """Represents the number as a triple tuple. |

1008 | n/a | |

1009 | n/a | To show the internals exactly as they are. |

1010 | n/a | """ |

1011 | n/a | return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp) |

1012 | n/a | |

1013 | n/a | def as_integer_ratio(self): |

1014 | n/a | """Express a finite Decimal instance in the form n / d. |

1015 | n/a | |

1016 | n/a | Returns a pair (n, d) of integers. When called on an infinity |

1017 | n/a | or NaN, raises OverflowError or ValueError respectively. |

1018 | n/a | |

1019 | n/a | >>> Decimal('3.14').as_integer_ratio() |

1020 | n/a | (157, 50) |

1021 | n/a | >>> Decimal('-123e5').as_integer_ratio() |

1022 | n/a | (-12300000, 1) |

1023 | n/a | >>> Decimal('0.00').as_integer_ratio() |

1024 | n/a | (0, 1) |

1025 | n/a | |

1026 | n/a | """ |

1027 | n/a | if self._is_special: |

1028 | n/a | if self.is_nan(): |

1029 | n/a | raise ValueError("cannot convert NaN to integer ratio") |

1030 | n/a | else: |

1031 | n/a | raise OverflowError("cannot convert Infinity to integer ratio") |

1032 | n/a | |

1033 | n/a | if not self: |

1034 | n/a | return 0, 1 |

1035 | n/a | |

1036 | n/a | # Find n, d in lowest terms such that abs(self) == n / d; |

1037 | n/a | # we'll deal with the sign later. |

1038 | n/a | n = int(self._int) |

1039 | n/a | if self._exp >= 0: |

1040 | n/a | # self is an integer. |

1041 | n/a | n, d = n * 10**self._exp, 1 |

1042 | n/a | else: |

1043 | n/a | # Find d2, d5 such that abs(self) = n / (2**d2 * 5**d5). |

1044 | n/a | d5 = -self._exp |

1045 | n/a | while d5 > 0 and n % 5 == 0: |

1046 | n/a | n //= 5 |

1047 | n/a | d5 -= 1 |

1048 | n/a | |

1049 | n/a | # (n & -n).bit_length() - 1 counts trailing zeros in binary |

1050 | n/a | # representation of n (provided n is nonzero). |

1051 | n/a | d2 = -self._exp |

1052 | n/a | shift2 = min((n & -n).bit_length() - 1, d2) |

1053 | n/a | if shift2: |

1054 | n/a | n >>= shift2 |

1055 | n/a | d2 -= shift2 |

1056 | n/a | |

1057 | n/a | d = 5**d5 << d2 |

1058 | n/a | |

1059 | n/a | if self._sign: |

1060 | n/a | n = -n |

1061 | n/a | return n, d |

1062 | n/a | |

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

1064 | n/a | """Represents the number as an instance of Decimal.""" |

1065 | n/a | # Invariant: eval(repr(d)) == d |

1066 | n/a | return "Decimal('%s')" % str(self) |

1067 | n/a | |

1068 | n/a | def __str__(self, eng=False, context=None): |

1069 | n/a | """Return string representation of the number in scientific notation. |

1070 | n/a | |

1071 | n/a | Captures all of the information in the underlying representation. |

1072 | n/a | """ |

1073 | n/a | |

1074 | n/a | sign = ['', '-'][self._sign] |

1075 | n/a | if self._is_special: |

1076 | n/a | if self._exp == 'F': |

1077 | n/a | return sign + 'Infinity' |

1078 | n/a | elif self._exp == 'n': |

1079 | n/a | return sign + 'NaN' + self._int |

1080 | n/a | else: # self._exp == 'N' |

1081 | n/a | return sign + 'sNaN' + self._int |

1082 | n/a | |

1083 | n/a | # number of digits of self._int to left of decimal point |

1084 | n/a | leftdigits = self._exp + len(self._int) |

1085 | n/a | |

1086 | n/a | # dotplace is number of digits of self._int to the left of the |

1087 | n/a | # decimal point in the mantissa of the output string (that is, |

1088 | n/a | # after adjusting the exponent) |

1089 | n/a | if self._exp <= 0 and leftdigits > -6: |

1090 | n/a | # no exponent required |

1091 | n/a | dotplace = leftdigits |

1092 | n/a | elif not eng: |

1093 | n/a | # usual scientific notation: 1 digit on left of the point |

1094 | n/a | dotplace = 1 |

1095 | n/a | elif self._int == '0': |

1096 | n/a | # engineering notation, zero |

1097 | n/a | dotplace = (leftdigits + 1) % 3 - 1 |

1098 | n/a | else: |

1099 | n/a | # engineering notation, nonzero |

1100 | n/a | dotplace = (leftdigits - 1) % 3 + 1 |

1101 | n/a | |

1102 | n/a | if dotplace <= 0: |

1103 | n/a | intpart = '0' |

1104 | n/a | fracpart = '.' + '0'*(-dotplace) + self._int |

1105 | n/a | elif dotplace >= len(self._int): |

1106 | n/a | intpart = self._int+'0'*(dotplace-len(self._int)) |

1107 | n/a | fracpart = '' |

1108 | n/a | else: |

1109 | n/a | intpart = self._int[:dotplace] |

1110 | n/a | fracpart = '.' + self._int[dotplace:] |

1111 | n/a | if leftdigits == dotplace: |

1112 | n/a | exp = '' |

1113 | n/a | else: |

1114 | n/a | if context is None: |

1115 | n/a | context = getcontext() |

1116 | n/a | exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace) |

1117 | n/a | |

1118 | n/a | return sign + intpart + fracpart + exp |

1119 | n/a | |

1120 | n/a | def to_eng_string(self, context=None): |

1121 | n/a | """Convert to a string, using engineering notation if an exponent is needed. |

1122 | n/a | |

1123 | n/a | Engineering notation has an exponent which is a multiple of 3. This |

1124 | n/a | can leave up to 3 digits to the left of the decimal place and may |

1125 | n/a | require the addition of either one or two trailing zeros. |

1126 | n/a | """ |

1127 | n/a | return self.__str__(eng=True, context=context) |

1128 | n/a | |

1129 | n/a | def __neg__(self, context=None): |

1130 | n/a | """Returns a copy with the sign switched. |

1131 | n/a | |

1132 | n/a | Rounds, if it has reason. |

1133 | n/a | """ |

1134 | n/a | if self._is_special: |

1135 | n/a | ans = self._check_nans(context=context) |

1136 | n/a | if ans: |

1137 | n/a | return ans |

1138 | n/a | |

1139 | n/a | if context is None: |

1140 | n/a | context = getcontext() |

1141 | n/a | |

1142 | n/a | if not self and context.rounding != ROUND_FLOOR: |

1143 | n/a | # -Decimal('0') is Decimal('0'), not Decimal('-0'), except |

1144 | n/a | # in ROUND_FLOOR rounding mode. |

1145 | n/a | ans = self.copy_abs() |

1146 | n/a | else: |

1147 | n/a | ans = self.copy_negate() |

1148 | n/a | |

1149 | n/a | return ans._fix(context) |

1150 | n/a | |

1151 | n/a | def __pos__(self, context=None): |

1152 | n/a | """Returns a copy, unless it is a sNaN. |

1153 | n/a | |

1154 | n/a | Rounds the number (if more than precision digits) |

1155 | n/a | """ |

1156 | n/a | if self._is_special: |

1157 | n/a | ans = self._check_nans(context=context) |

1158 | n/a | if ans: |

1159 | n/a | return ans |

1160 | n/a | |

1161 | n/a | if context is None: |

1162 | n/a | context = getcontext() |

1163 | n/a | |

1164 | n/a | if not self and context.rounding != ROUND_FLOOR: |

1165 | n/a | # + (-0) = 0, except in ROUND_FLOOR rounding mode. |

1166 | n/a | ans = self.copy_abs() |

1167 | n/a | else: |

1168 | n/a | ans = Decimal(self) |

1169 | n/a | |

1170 | n/a | return ans._fix(context) |

1171 | n/a | |

1172 | n/a | def __abs__(self, round=True, context=None): |

1173 | n/a | """Returns the absolute value of self. |

1174 | n/a | |

1175 | n/a | If the keyword argument 'round' is false, do not round. The |

1176 | n/a | expression self.__abs__(round=False) is equivalent to |

1177 | n/a | self.copy_abs(). |

1178 | n/a | """ |

1179 | n/a | if not round: |

1180 | n/a | return self.copy_abs() |

1181 | n/a | |

1182 | n/a | if self._is_special: |

1183 | n/a | ans = self._check_nans(context=context) |

1184 | n/a | if ans: |

1185 | n/a | return ans |

1186 | n/a | |

1187 | n/a | if self._sign: |

1188 | n/a | ans = self.__neg__(context=context) |

1189 | n/a | else: |

1190 | n/a | ans = self.__pos__(context=context) |

1191 | n/a | |

1192 | n/a | return ans |

1193 | n/a | |

1194 | n/a | def __add__(self, other, context=None): |

1195 | n/a | """Returns self + other. |

1196 | n/a | |

1197 | n/a | -INF + INF (or the reverse) cause InvalidOperation errors. |

1198 | n/a | """ |

1199 | n/a | other = _convert_other(other) |

1200 | n/a | if other is NotImplemented: |

1201 | n/a | return other |

1202 | n/a | |

1203 | n/a | if context is None: |

1204 | n/a | context = getcontext() |

1205 | n/a | |

1206 | n/a | if self._is_special or other._is_special: |

1207 | n/a | ans = self._check_nans(other, context) |

1208 | n/a | if ans: |

1209 | n/a | return ans |

1210 | n/a | |

1211 | n/a | if self._isinfinity(): |

1212 | n/a | # If both INF, same sign => same as both, opposite => error. |

1213 | n/a | if self._sign != other._sign and other._isinfinity(): |

1214 | n/a | return context._raise_error(InvalidOperation, '-INF + INF') |

1215 | n/a | return Decimal(self) |

1216 | n/a | if other._isinfinity(): |

1217 | n/a | return Decimal(other) # Can't both be infinity here |

1218 | n/a | |

1219 | n/a | exp = min(self._exp, other._exp) |

1220 | n/a | negativezero = 0 |

1221 | n/a | if context.rounding == ROUND_FLOOR and self._sign != other._sign: |

1222 | n/a | # If the answer is 0, the sign should be negative, in this case. |

1223 | n/a | negativezero = 1 |

1224 | n/a | |

1225 | n/a | if not self and not other: |

1226 | n/a | sign = min(self._sign, other._sign) |

1227 | n/a | if negativezero: |

1228 | n/a | sign = 1 |

1229 | n/a | ans = _dec_from_triple(sign, '0', exp) |

1230 | n/a | ans = ans._fix(context) |

1231 | n/a | return ans |

1232 | n/a | if not self: |

1233 | n/a | exp = max(exp, other._exp - context.prec-1) |

1234 | n/a | ans = other._rescale(exp, context.rounding) |

1235 | n/a | ans = ans._fix(context) |

1236 | n/a | return ans |

1237 | n/a | if not other: |

1238 | n/a | exp = max(exp, self._exp - context.prec-1) |

1239 | n/a | ans = self._rescale(exp, context.rounding) |

1240 | n/a | ans = ans._fix(context) |

1241 | n/a | return ans |

1242 | n/a | |

1243 | n/a | op1 = _WorkRep(self) |

1244 | n/a | op2 = _WorkRep(other) |

1245 | n/a | op1, op2 = _normalize(op1, op2, context.prec) |

1246 | n/a | |

1247 | n/a | result = _WorkRep() |

1248 | n/a | if op1.sign != op2.sign: |

1249 | n/a | # Equal and opposite |

1250 | n/a | if op1.int == op2.int: |

1251 | n/a | ans = _dec_from_triple(negativezero, '0', exp) |

1252 | n/a | ans = ans._fix(context) |

1253 | n/a | return ans |

1254 | n/a | if op1.int < op2.int: |

1255 | n/a | op1, op2 = op2, op1 |

1256 | n/a | # OK, now abs(op1) > abs(op2) |

1257 | n/a | if op1.sign == 1: |

1258 | n/a | result.sign = 1 |

1259 | n/a | op1.sign, op2.sign = op2.sign, op1.sign |

1260 | n/a | else: |

1261 | n/a | result.sign = 0 |

1262 | n/a | # So we know the sign, and op1 > 0. |

1263 | n/a | elif op1.sign == 1: |

1264 | n/a | result.sign = 1 |

1265 | n/a | op1.sign, op2.sign = (0, 0) |

1266 | n/a | else: |

1267 | n/a | result.sign = 0 |

1268 | n/a | # Now, op1 > abs(op2) > 0 |

1269 | n/a | |

1270 | n/a | if op2.sign == 0: |

1271 | n/a | result.int = op1.int + op2.int |

1272 | n/a | else: |

1273 | n/a | result.int = op1.int - op2.int |

1274 | n/a | |

1275 | n/a | result.exp = op1.exp |

1276 | n/a | ans = Decimal(result) |

1277 | n/a | ans = ans._fix(context) |

1278 | n/a | return ans |

1279 | n/a | |

1280 | n/a | __radd__ = __add__ |

1281 | n/a | |

1282 | n/a | def __sub__(self, other, context=None): |

1283 | n/a | """Return self - other""" |

1284 | n/a | other = _convert_other(other) |

1285 | n/a | if other is NotImplemented: |

1286 | n/a | return other |

1287 | n/a | |

1288 | n/a | if self._is_special or other._is_special: |

1289 | n/a | ans = self._check_nans(other, context=context) |

1290 | n/a | if ans: |

1291 | n/a | return ans |

1292 | n/a | |

1293 | n/a | # self - other is computed as self + other.copy_negate() |

1294 | n/a | return self.__add__(other.copy_negate(), context=context) |

1295 | n/a | |

1296 | n/a | def __rsub__(self, other, context=None): |

1297 | n/a | """Return other - self""" |

1298 | n/a | other = _convert_other(other) |

1299 | n/a | if other is NotImplemented: |

1300 | n/a | return other |

1301 | n/a | |

1302 | n/a | return other.__sub__(self, context=context) |

1303 | n/a | |

1304 | n/a | def __mul__(self, other, context=None): |

1305 | n/a | """Return self * other. |

1306 | n/a | |

1307 | n/a | (+-) INF * 0 (or its reverse) raise InvalidOperation. |

1308 | n/a | """ |

1309 | n/a | other = _convert_other(other) |

1310 | n/a | if other is NotImplemented: |

1311 | n/a | return other |

1312 | n/a | |

1313 | n/a | if context is None: |

1314 | n/a | context = getcontext() |

1315 | n/a | |

1316 | n/a | resultsign = self._sign ^ other._sign |

1317 | n/a | |

1318 | n/a | if self._is_special or other._is_special: |

1319 | n/a | ans = self._check_nans(other, context) |

1320 | n/a | if ans: |

1321 | n/a | return ans |

1322 | n/a | |

1323 | n/a | if self._isinfinity(): |

1324 | n/a | if not other: |

1325 | n/a | return context._raise_error(InvalidOperation, '(+-)INF * 0') |

1326 | n/a | return _SignedInfinity[resultsign] |

1327 | n/a | |

1328 | n/a | if other._isinfinity(): |

1329 | n/a | if not self: |

1330 | n/a | return context._raise_error(InvalidOperation, '0 * (+-)INF') |

1331 | n/a | return _SignedInfinity[resultsign] |

1332 | n/a | |

1333 | n/a | resultexp = self._exp + other._exp |

1334 | n/a | |

1335 | n/a | # Special case for multiplying by zero |

1336 | n/a | if not self or not other: |

1337 | n/a | ans = _dec_from_triple(resultsign, '0', resultexp) |

1338 | n/a | # Fixing in case the exponent is out of bounds |

1339 | n/a | ans = ans._fix(context) |

1340 | n/a | return ans |

1341 | n/a | |

1342 | n/a | # Special case for multiplying by power of 10 |

1343 | n/a | if self._int == '1': |

1344 | n/a | ans = _dec_from_triple(resultsign, other._int, resultexp) |

1345 | n/a | ans = ans._fix(context) |

1346 | n/a | return ans |

1347 | n/a | if other._int == '1': |

1348 | n/a | ans = _dec_from_triple(resultsign, self._int, resultexp) |

1349 | n/a | ans = ans._fix(context) |

1350 | n/a | return ans |

1351 | n/a | |

1352 | n/a | op1 = _WorkRep(self) |

1353 | n/a | op2 = _WorkRep(other) |

1354 | n/a | |

1355 | n/a | ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp) |

1356 | n/a | ans = ans._fix(context) |

1357 | n/a | |

1358 | n/a | return ans |

1359 | n/a | __rmul__ = __mul__ |

1360 | n/a | |

1361 | n/a | def __truediv__(self, other, context=None): |

1362 | n/a | """Return self / other.""" |

1363 | n/a | other = _convert_other(other) |

1364 | n/a | if other is NotImplemented: |

1365 | n/a | return NotImplemented |

1366 | n/a | |

1367 | n/a | if context is None: |

1368 | n/a | context = getcontext() |

1369 | n/a | |

1370 | n/a | sign = self._sign ^ other._sign |

1371 | n/a | |

1372 | n/a | if self._is_special or other._is_special: |

1373 | n/a | ans = self._check_nans(other, context) |

1374 | n/a | if ans: |

1375 | n/a | return ans |

1376 | n/a | |

1377 | n/a | if self._isinfinity() and other._isinfinity(): |

1378 | n/a | return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') |

1379 | n/a | |

1380 | n/a | if self._isinfinity(): |

1381 | n/a | return _SignedInfinity[sign] |

1382 | n/a | |

1383 | n/a | if other._isinfinity(): |

1384 | n/a | context._raise_error(Clamped, 'Division by infinity') |

1385 | n/a | return _dec_from_triple(sign, '0', context.Etiny()) |

1386 | n/a | |

1387 | n/a | # Special cases for zeroes |

1388 | n/a | if not other: |

1389 | n/a | if not self: |

1390 | n/a | return context._raise_error(DivisionUndefined, '0 / 0') |

1391 | n/a | return context._raise_error(DivisionByZero, 'x / 0', sign) |

1392 | n/a | |

1393 | n/a | if not self: |

1394 | n/a | exp = self._exp - other._exp |

1395 | n/a | coeff = 0 |

1396 | n/a | else: |

1397 | n/a | # OK, so neither = 0, INF or NaN |

1398 | n/a | shift = len(other._int) - len(self._int) + context.prec + 1 |

1399 | n/a | exp = self._exp - other._exp - shift |

1400 | n/a | op1 = _WorkRep(self) |

1401 | n/a | op2 = _WorkRep(other) |

1402 | n/a | if shift >= 0: |

1403 | n/a | coeff, remainder = divmod(op1.int * 10**shift, op2.int) |

1404 | n/a | else: |

1405 | n/a | coeff, remainder = divmod(op1.int, op2.int * 10**-shift) |

1406 | n/a | if remainder: |

1407 | n/a | # result is not exact; adjust to ensure correct rounding |

1408 | n/a | if coeff % 5 == 0: |

1409 | n/a | coeff += 1 |

1410 | n/a | else: |

1411 | n/a | # result is exact; get as close to ideal exponent as possible |

1412 | n/a | ideal_exp = self._exp - other._exp |

1413 | n/a | while exp < ideal_exp and coeff % 10 == 0: |

1414 | n/a | coeff //= 10 |

1415 | n/a | exp += 1 |

1416 | n/a | |

1417 | n/a | ans = _dec_from_triple(sign, str(coeff), exp) |

1418 | n/a | return ans._fix(context) |

1419 | n/a | |

1420 | n/a | def _divide(self, other, context): |

1421 | n/a | """Return (self // other, self % other), to context.prec precision. |

1422 | n/a | |

1423 | n/a | Assumes that neither self nor other is a NaN, that self is not |

1424 | n/a | infinite and that other is nonzero. |

1425 | n/a | """ |

1426 | n/a | sign = self._sign ^ other._sign |

1427 | n/a | if other._isinfinity(): |

1428 | n/a | ideal_exp = self._exp |

1429 | n/a | else: |

1430 | n/a | ideal_exp = min(self._exp, other._exp) |

1431 | n/a | |

1432 | n/a | expdiff = self.adjusted() - other.adjusted() |

1433 | n/a | if not self or other._isinfinity() or expdiff <= -2: |

1434 | n/a | return (_dec_from_triple(sign, '0', 0), |

1435 | n/a | self._rescale(ideal_exp, context.rounding)) |

1436 | n/a | if expdiff <= context.prec: |

1437 | n/a | op1 = _WorkRep(self) |

1438 | n/a | op2 = _WorkRep(other) |

1439 | n/a | if op1.exp >= op2.exp: |

1440 | n/a | op1.int *= 10**(op1.exp - op2.exp) |

1441 | n/a | else: |

1442 | n/a | op2.int *= 10**(op2.exp - op1.exp) |

1443 | n/a | q, r = divmod(op1.int, op2.int) |

1444 | n/a | if q < 10**context.prec: |

1445 | n/a | return (_dec_from_triple(sign, str(q), 0), |

1446 | n/a | _dec_from_triple(self._sign, str(r), ideal_exp)) |

1447 | n/a | |

1448 | n/a | # Here the quotient is too large to be representable |

1449 | n/a | ans = context._raise_error(DivisionImpossible, |

1450 | n/a | 'quotient too large in //, % or divmod') |

1451 | n/a | return ans, ans |

1452 | n/a | |

1453 | n/a | def __rtruediv__(self, other, context=None): |

1454 | n/a | """Swaps self/other and returns __truediv__.""" |

1455 | n/a | other = _convert_other(other) |

1456 | n/a | if other is NotImplemented: |

1457 | n/a | return other |

1458 | n/a | return other.__truediv__(self, context=context) |

1459 | n/a | |

1460 | n/a | def __divmod__(self, other, context=None): |

1461 | n/a | """ |

1462 | n/a | Return (self // other, self % other) |

1463 | n/a | """ |

1464 | n/a | other = _convert_other(other) |

1465 | n/a | if other is NotImplemented: |

1466 | n/a | return other |

1467 | n/a | |

1468 | n/a | if context is None: |

1469 | n/a | context = getcontext() |

1470 | n/a | |

1471 | n/a | ans = self._check_nans(other, context) |

1472 | n/a | if ans: |

1473 | n/a | return (ans, ans) |

1474 | n/a | |

1475 | n/a | sign = self._sign ^ other._sign |

1476 | n/a | if self._isinfinity(): |

1477 | n/a | if other._isinfinity(): |

1478 | n/a | ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') |

1479 | n/a | return ans, ans |

1480 | n/a | else: |

1481 | n/a | return (_SignedInfinity[sign], |

1482 | n/a | context._raise_error(InvalidOperation, 'INF % x')) |

1483 | n/a | |

1484 | n/a | if not other: |

1485 | n/a | if not self: |

1486 | n/a | ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') |

1487 | n/a | return ans, ans |

1488 | n/a | else: |

1489 | n/a | return (context._raise_error(DivisionByZero, 'x // 0', sign), |

1490 | n/a | context._raise_error(InvalidOperation, 'x % 0')) |

1491 | n/a | |

1492 | n/a | quotient, remainder = self._divide(other, context) |

1493 | n/a | remainder = remainder._fix(context) |

1494 | n/a | return quotient, remainder |

1495 | n/a | |

1496 | n/a | def __rdivmod__(self, other, context=None): |

1497 | n/a | """Swaps self/other and returns __divmod__.""" |

1498 | n/a | other = _convert_other(other) |

1499 | n/a | if other is NotImplemented: |

1500 | n/a | return other |

1501 | n/a | return other.__divmod__(self, context=context) |

1502 | n/a | |

1503 | n/a | def __mod__(self, other, context=None): |

1504 | n/a | """ |

1505 | n/a | self % other |

1506 | n/a | """ |

1507 | n/a | other = _convert_other(other) |

1508 | n/a | if other is NotImplemented: |

1509 | n/a | return other |

1510 | n/a | |

1511 | n/a | if context is None: |

1512 | n/a | context = getcontext() |

1513 | n/a | |

1514 | n/a | ans = self._check_nans(other, context) |

1515 | n/a | if ans: |

1516 | n/a | return ans |

1517 | n/a | |

1518 | n/a | if self._isinfinity(): |

1519 | n/a | return context._raise_error(InvalidOperation, 'INF % x') |

1520 | n/a | elif not other: |

1521 | n/a | if self: |

1522 | n/a | return context._raise_error(InvalidOperation, 'x % 0') |

1523 | n/a | else: |

1524 | n/a | return context._raise_error(DivisionUndefined, '0 % 0') |

1525 | n/a | |

1526 | n/a | remainder = self._divide(other, context)[1] |

1527 | n/a | remainder = remainder._fix(context) |

1528 | n/a | return remainder |

1529 | n/a | |

1530 | n/a | def __rmod__(self, other, context=None): |

1531 | n/a | """Swaps self/other and returns __mod__.""" |

1532 | n/a | other = _convert_other(other) |

1533 | n/a | if other is NotImplemented: |

1534 | n/a | return other |

1535 | n/a | return other.__mod__(self, context=context) |

1536 | n/a | |

1537 | n/a | def remainder_near(self, other, context=None): |

1538 | n/a | """ |

1539 | n/a | Remainder nearest to 0- abs(remainder-near) <= other/2 |

1540 | n/a | """ |

1541 | n/a | if context is None: |

1542 | n/a | context = getcontext() |

1543 | n/a | |

1544 | n/a | other = _convert_other(other, raiseit=True) |

1545 | n/a | |

1546 | n/a | ans = self._check_nans(other, context) |

1547 | n/a | if ans: |

1548 | n/a | return ans |

1549 | n/a | |

1550 | n/a | # self == +/-infinity -> InvalidOperation |

1551 | n/a | if self._isinfinity(): |

1552 | n/a | return context._raise_error(InvalidOperation, |

1553 | n/a | 'remainder_near(infinity, x)') |

1554 | n/a | |

1555 | n/a | # other == 0 -> either InvalidOperation or DivisionUndefined |

1556 | n/a | if not other: |

1557 | n/a | if self: |

1558 | n/a | return context._raise_error(InvalidOperation, |

1559 | n/a | 'remainder_near(x, 0)') |

1560 | n/a | else: |

1561 | n/a | return context._raise_error(DivisionUndefined, |

1562 | n/a | 'remainder_near(0, 0)') |

1563 | n/a | |

1564 | n/a | # other = +/-infinity -> remainder = self |

1565 | n/a | if other._isinfinity(): |

1566 | n/a | ans = Decimal(self) |

1567 | n/a | return ans._fix(context) |

1568 | n/a | |

1569 | n/a | # self = 0 -> remainder = self, with ideal exponent |

1570 | n/a | ideal_exponent = min(self._exp, other._exp) |

1571 | n/a | if not self: |

1572 | n/a | ans = _dec_from_triple(self._sign, '0', ideal_exponent) |

1573 | n/a | return ans._fix(context) |

1574 | n/a | |

1575 | n/a | # catch most cases of large or small quotient |

1576 | n/a | expdiff = self.adjusted() - other.adjusted() |

1577 | n/a | if expdiff >= context.prec + 1: |

1578 | n/a | # expdiff >= prec+1 => abs(self/other) > 10**prec |

1579 | n/a | return context._raise_error(DivisionImpossible) |

1580 | n/a | if expdiff <= -2: |

1581 | n/a | # expdiff <= -2 => abs(self/other) < 0.1 |

1582 | n/a | ans = self._rescale(ideal_exponent, context.rounding) |

1583 | n/a | return ans._fix(context) |

1584 | n/a | |

1585 | n/a | # adjust both arguments to have the same exponent, then divide |

1586 | n/a | op1 = _WorkRep(self) |

1587 | n/a | op2 = _WorkRep(other) |

1588 | n/a | if op1.exp >= op2.exp: |

1589 | n/a | op1.int *= 10**(op1.exp - op2.exp) |

1590 | n/a | else: |

1591 | n/a | op2.int *= 10**(op2.exp - op1.exp) |

1592 | n/a | q, r = divmod(op1.int, op2.int) |

1593 | n/a | # remainder is r*10**ideal_exponent; other is +/-op2.int * |

1594 | n/a | # 10**ideal_exponent. Apply correction to ensure that |

1595 | n/a | # abs(remainder) <= abs(other)/2 |

1596 | n/a | if 2*r + (q&1) > op2.int: |

1597 | n/a | r -= op2.int |

1598 | n/a | q += 1 |

1599 | n/a | |

1600 | n/a | if q >= 10**context.prec: |

1601 | n/a | return context._raise_error(DivisionImpossible) |

1602 | n/a | |

1603 | n/a | # result has same sign as self unless r is negative |

1604 | n/a | sign = self._sign |

1605 | n/a | if r < 0: |

1606 | n/a | sign = 1-sign |

1607 | n/a | r = -r |

1608 | n/a | |

1609 | n/a | ans = _dec_from_triple(sign, str(r), ideal_exponent) |

1610 | n/a | return ans._fix(context) |

1611 | n/a | |

1612 | n/a | def __floordiv__(self, other, context=None): |

1613 | n/a | """self // other""" |

1614 | n/a | other = _convert_other(other) |

1615 | n/a | if other is NotImplemented: |

1616 | n/a | return other |

1617 | n/a | |

1618 | n/a | if context is None: |

1619 | n/a | context = getcontext() |

1620 | n/a | |

1621 | n/a | ans = self._check_nans(other, context) |

1622 | n/a | if ans: |

1623 | n/a | return ans |

1624 | n/a | |

1625 | n/a | if self._isinfinity(): |

1626 | n/a | if other._isinfinity(): |

1627 | n/a | return context._raise_error(InvalidOperation, 'INF // INF') |

1628 | n/a | else: |

1629 | n/a | return _SignedInfinity[self._sign ^ other._sign] |

1630 | n/a | |

1631 | n/a | if not other: |

1632 | n/a | if self: |

1633 | n/a | return context._raise_error(DivisionByZero, 'x // 0', |

1634 | n/a | self._sign ^ other._sign) |

1635 | n/a | else: |

1636 | n/a | return context._raise_error(DivisionUndefined, '0 // 0') |

1637 | n/a | |

1638 | n/a | return self._divide(other, context)[0] |

1639 | n/a | |

1640 | n/a | def __rfloordiv__(self, other, context=None): |

1641 | n/a | """Swaps self/other and returns __floordiv__.""" |

1642 | n/a | other = _convert_other(other) |

1643 | n/a | if other is NotImplemented: |

1644 | n/a | return other |

1645 | n/a | return other.__floordiv__(self, context=context) |

1646 | n/a | |

1647 | n/a | def __float__(self): |

1648 | n/a | """Float representation.""" |

1649 | n/a | if self._isnan(): |

1650 | n/a | if self.is_snan(): |

1651 | n/a | raise ValueError("Cannot convert signaling NaN to float") |

1652 | n/a | s = "-nan" if self._sign else "nan" |

1653 | n/a | else: |

1654 | n/a | s = str(self) |

1655 | n/a | return float(s) |

1656 | n/a | |

1657 | n/a | def __int__(self): |

1658 | n/a | """Converts self to an int, truncating if necessary.""" |

1659 | n/a | if self._is_special: |

1660 | n/a | if self._isnan(): |

1661 | n/a | raise ValueError("Cannot convert NaN to integer") |

1662 | n/a | elif self._isinfinity(): |

1663 | n/a | raise OverflowError("Cannot convert infinity to integer") |

1664 | n/a | s = (-1)**self._sign |

1665 | n/a | if self._exp >= 0: |

1666 | n/a | return s*int(self._int)*10**self._exp |

1667 | n/a | else: |

1668 | n/a | return s*int(self._int[:self._exp] or '0') |

1669 | n/a | |

1670 | n/a | __trunc__ = __int__ |

1671 | n/a | |

1672 | n/a | def real(self): |

1673 | n/a | return self |

1674 | n/a | real = property(real) |

1675 | n/a | |

1676 | n/a | def imag(self): |

1677 | n/a | return Decimal(0) |

1678 | n/a | imag = property(imag) |

1679 | n/a | |

1680 | n/a | def conjugate(self): |

1681 | n/a | return self |

1682 | n/a | |

1683 | n/a | def __complex__(self): |

1684 | n/a | return complex(float(self)) |

1685 | n/a | |

1686 | n/a | def _fix_nan(self, context): |

1687 | n/a | """Decapitate the payload of a NaN to fit the context""" |

1688 | n/a | payload = self._int |

1689 | n/a | |

1690 | n/a | # maximum length of payload is precision if clamp=0, |

1691 | n/a | # precision-1 if clamp=1. |

1692 | n/a | max_payload_len = context.prec - context.clamp |

1693 | n/a | if len(payload) > max_payload_len: |

1694 | n/a | payload = payload[len(payload)-max_payload_len:].lstrip('0') |

1695 | n/a | return _dec_from_triple(self._sign, payload, self._exp, True) |

1696 | n/a | return Decimal(self) |

1697 | n/a | |

1698 | n/a | def _fix(self, context): |

1699 | n/a | """Round if it is necessary to keep self within prec precision. |

1700 | n/a | |

1701 | n/a | Rounds and fixes the exponent. Does not raise on a sNaN. |

1702 | n/a | |

1703 | n/a | Arguments: |

1704 | n/a | self - Decimal instance |

1705 | n/a | context - context used. |

1706 | n/a | """ |

1707 | n/a | |

1708 | n/a | if self._is_special: |

1709 | n/a | if self._isnan(): |

1710 | n/a | # decapitate payload if necessary |

1711 | n/a | return self._fix_nan(context) |

1712 | n/a | else: |

1713 | n/a | # self is +/-Infinity; return unaltered |

1714 | n/a | return Decimal(self) |

1715 | n/a | |

1716 | n/a | # if self is zero then exponent should be between Etiny and |

1717 | n/a | # Emax if clamp==0, and between Etiny and Etop if clamp==1. |

1718 | n/a | Etiny = context.Etiny() |

1719 | n/a | Etop = context.Etop() |

1720 | n/a | if not self: |

1721 | n/a | exp_max = [context.Emax, Etop][context.clamp] |

1722 | n/a | new_exp = min(max(self._exp, Etiny), exp_max) |

1723 | n/a | if new_exp != self._exp: |

1724 | n/a | context._raise_error(Clamped) |

1725 | n/a | return _dec_from_triple(self._sign, '0', new_exp) |

1726 | n/a | else: |

1727 | n/a | return Decimal(self) |

1728 | n/a | |

1729 | n/a | # exp_min is the smallest allowable exponent of the result, |

1730 | n/a | # equal to max(self.adjusted()-context.prec+1, Etiny) |

1731 | n/a | exp_min = len(self._int) + self._exp - context.prec |

1732 | n/a | if exp_min > Etop: |

1733 | n/a | # overflow: exp_min > Etop iff self.adjusted() > Emax |

1734 | n/a | ans = context._raise_error(Overflow, 'above Emax', self._sign) |

1735 | n/a | context._raise_error(Inexact) |

1736 | n/a | context._raise_error(Rounded) |

1737 | n/a | return ans |

1738 | n/a | |

1739 | n/a | self_is_subnormal = exp_min < Etiny |

1740 | n/a | if self_is_subnormal: |

1741 | n/a | exp_min = Etiny |

1742 | n/a | |

1743 | n/a | # round if self has too many digits |

1744 | n/a | if self._exp < exp_min: |

1745 | n/a | digits = len(self._int) + self._exp - exp_min |

1746 | n/a | if digits < 0: |

1747 | n/a | self = _dec_from_triple(self._sign, '1', exp_min-1) |

1748 | n/a | digits = 0 |

1749 | n/a | rounding_method = self._pick_rounding_function[context.rounding] |

1750 | n/a | changed = rounding_method(self, digits) |

1751 | n/a | coeff = self._int[:digits] or '0' |

1752 | n/a | if changed > 0: |

1753 | n/a | coeff = str(int(coeff)+1) |

1754 | n/a | if len(coeff) > context.prec: |

1755 | n/a | coeff = coeff[:-1] |

1756 | n/a | exp_min += 1 |

1757 | n/a | |

1758 | n/a | # check whether the rounding pushed the exponent out of range |

1759 | n/a | if exp_min > Etop: |

1760 | n/a | ans = context._raise_error(Overflow, 'above Emax', self._sign) |

1761 | n/a | else: |

1762 | n/a | ans = _dec_from_triple(self._sign, coeff, exp_min) |

1763 | n/a | |

1764 | n/a | # raise the appropriate signals, taking care to respect |

1765 | n/a | # the precedence described in the specification |

1766 | n/a | if changed and self_is_subnormal: |

1767 | n/a | context._raise_error(Underflow) |

1768 | n/a | if self_is_subnormal: |

1769 | n/a | context._raise_error(Subnormal) |

1770 | n/a | if changed: |

1771 | n/a | context._raise_error(Inexact) |

1772 | n/a | context._raise_error(Rounded) |

1773 | n/a | if not ans: |

1774 | n/a | # raise Clamped on underflow to 0 |

1775 | n/a | context._raise_error(Clamped) |

1776 | n/a | return ans |

1777 | n/a | |

1778 | n/a | if self_is_subnormal: |

1779 | n/a | context._raise_error(Subnormal) |

1780 | n/a | |

1781 | n/a | # fold down if clamp == 1 and self has too few digits |

1782 | n/a | if context.clamp == 1 and self._exp > Etop: |

1783 | n/a | context._raise_error(Clamped) |

1784 | n/a | self_padded = self._int + '0'*(self._exp - Etop) |

1785 | n/a | return _dec_from_triple(self._sign, self_padded, Etop) |

1786 | n/a | |

1787 | n/a | # here self was representable to begin with; return unchanged |

1788 | n/a | return Decimal(self) |

1789 | n/a | |

1790 | n/a | # for each of the rounding functions below: |

1791 | n/a | # self is a finite, nonzero Decimal |

1792 | n/a | # prec is an integer satisfying 0 <= prec < len(self._int) |

1793 | n/a | # |

1794 | n/a | # each function returns either -1, 0, or 1, as follows: |

1795 | n/a | # 1 indicates that self should be rounded up (away from zero) |

1796 | n/a | # 0 indicates that self should be truncated, and that all the |

1797 | n/a | # digits to be truncated are zeros (so the value is unchanged) |

1798 | n/a | # -1 indicates that there are nonzero digits to be truncated |

1799 | n/a | |

1800 | n/a | def _round_down(self, prec): |

1801 | n/a | """Also known as round-towards-0, truncate.""" |

1802 | n/a | if _all_zeros(self._int, prec): |

1803 | n/a | return 0 |

1804 | n/a | else: |

1805 | n/a | return -1 |

1806 | n/a | |

1807 | n/a | def _round_up(self, prec): |

1808 | n/a | """Rounds away from 0.""" |

1809 | n/a | return -self._round_down(prec) |

1810 | n/a | |

1811 | n/a | def _round_half_up(self, prec): |

1812 | n/a | """Rounds 5 up (away from 0)""" |

1813 | n/a | if self._int[prec] in '56789': |

1814 | n/a | return 1 |

1815 | n/a | elif _all_zeros(self._int, prec): |

1816 | n/a | return 0 |

1817 | n/a | else: |

1818 | n/a | return -1 |

1819 | n/a | |

1820 | n/a | def _round_half_down(self, prec): |

1821 | n/a | """Round 5 down""" |

1822 | n/a | if _exact_half(self._int, prec): |

1823 | n/a | return -1 |

1824 | n/a | else: |

1825 | n/a | return self._round_half_up(prec) |

1826 | n/a | |

1827 | n/a | def _round_half_even(self, prec): |

1828 | n/a | """Round 5 to even, rest to nearest.""" |

1829 | n/a | if _exact_half(self._int, prec) and \ |

1830 | n/a | (prec == 0 or self._int[prec-1] in '02468'): |

1831 | n/a | return -1 |

1832 | n/a | else: |

1833 | n/a | return self._round_half_up(prec) |

1834 | n/a | |

1835 | n/a | def _round_ceiling(self, prec): |

1836 | n/a | """Rounds up (not away from 0 if negative.)""" |

1837 | n/a | if self._sign: |

1838 | n/a | return self._round_down(prec) |

1839 | n/a | else: |

1840 | n/a | return -self._round_down(prec) |

1841 | n/a | |

1842 | n/a | def _round_floor(self, prec): |

1843 | n/a | """Rounds down (not towards 0 if negative)""" |

1844 | n/a | if not self._sign: |

1845 | n/a | return self._round_down(prec) |

1846 | n/a | else: |

1847 | n/a | return -self._round_down(prec) |

1848 | n/a | |

1849 | n/a | def _round_05up(self, prec): |

1850 | n/a | """Round down unless digit prec-1 is 0 or 5.""" |

1851 | n/a | if prec and self._int[prec-1] not in '05': |

1852 | n/a | return self._round_down(prec) |

1853 | n/a | else: |

1854 | n/a | return -self._round_down(prec) |

1855 | n/a | |

1856 | n/a | _pick_rounding_function = dict( |

1857 | n/a | ROUND_DOWN = _round_down, |

1858 | n/a | ROUND_UP = _round_up, |

1859 | n/a | ROUND_HALF_UP = _round_half_up, |

1860 | n/a | ROUND_HALF_DOWN = _round_half_down, |

1861 | n/a | ROUND_HALF_EVEN = _round_half_even, |

1862 | n/a | ROUND_CEILING = _round_ceiling, |

1863 | n/a | ROUND_FLOOR = _round_floor, |

1864 | n/a | ROUND_05UP = _round_05up, |

1865 | n/a | ) |

1866 | n/a | |

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

1868 | n/a | """Round self to the nearest integer, or to a given precision. |

1869 | n/a | |

1870 | n/a | If only one argument is supplied, round a finite Decimal |

1871 | n/a | instance self to the nearest integer. If self is infinite or |

1872 | n/a | a NaN then a Python exception is raised. If self is finite |

1873 | n/a | and lies exactly halfway between two integers then it is |

1874 | n/a | rounded to the integer with even last digit. |

1875 | n/a | |

1876 | n/a | >>> round(Decimal('123.456')) |

1877 | n/a | 123 |

1878 | n/a | >>> round(Decimal('-456.789')) |

1879 | n/a | -457 |

1880 | n/a | >>> round(Decimal('-3.0')) |

1881 | n/a | -3 |

1882 | n/a | >>> round(Decimal('2.5')) |

1883 | n/a | 2 |

1884 | n/a | >>> round(Decimal('3.5')) |

1885 | n/a | 4 |

1886 | n/a | >>> round(Decimal('Inf')) |

1887 | n/a | Traceback (most recent call last): |

1888 | n/a | ... |

1889 | n/a | OverflowError: cannot round an infinity |

1890 | n/a | >>> round(Decimal('NaN')) |

1891 | n/a | Traceback (most recent call last): |

1892 | n/a | ... |

1893 | n/a | ValueError: cannot round a NaN |

1894 | n/a | |

1895 | n/a | If a second argument n is supplied, self is rounded to n |

1896 | n/a | decimal places using the rounding mode for the current |

1897 | n/a | context. |

1898 | n/a | |

1899 | n/a | For an integer n, round(self, -n) is exactly equivalent to |

1900 | n/a | self.quantize(Decimal('1En')). |

1901 | n/a | |

1902 | n/a | >>> round(Decimal('123.456'), 0) |

1903 | n/a | Decimal('123') |

1904 | n/a | >>> round(Decimal('123.456'), 2) |

1905 | n/a | Decimal('123.46') |

1906 | n/a | >>> round(Decimal('123.456'), -2) |

1907 | n/a | Decimal('1E+2') |

1908 | n/a | >>> round(Decimal('-Infinity'), 37) |

1909 | n/a | Decimal('NaN') |

1910 | n/a | >>> round(Decimal('sNaN123'), 0) |

1911 | n/a | Decimal('NaN123') |

1912 | n/a | |

1913 | n/a | """ |

1914 | n/a | if n is not None: |

1915 | n/a | # two-argument form: use the equivalent quantize call |

1916 | n/a | if not isinstance(n, int): |

1917 | n/a | raise TypeError('Second argument to round should be integral') |

1918 | n/a | exp = _dec_from_triple(0, '1', -n) |

1919 | n/a | return self.quantize(exp) |

1920 | n/a | |

1921 | n/a | # one-argument form |

1922 | n/a | if self._is_special: |

1923 | n/a | if self.is_nan(): |

1924 | n/a | raise ValueError("cannot round a NaN") |

1925 | n/a | else: |

1926 | n/a | raise OverflowError("cannot round an infinity") |

1927 | n/a | return int(self._rescale(0, ROUND_HALF_EVEN)) |

1928 | n/a | |

1929 | n/a | def __floor__(self): |

1930 | n/a | """Return the floor of self, as an integer. |

1931 | n/a | |

1932 | n/a | For a finite Decimal instance self, return the greatest |

1933 | n/a | integer n such that n <= self. If self is infinite or a NaN |

1934 | n/a | then a Python exception is raised. |

1935 | n/a | |

1936 | n/a | """ |

1937 | n/a | if self._is_special: |

1938 | n/a | if self.is_nan(): |

1939 | n/a | raise ValueError("cannot round a NaN") |

1940 | n/a | else: |

1941 | n/a | raise OverflowError("cannot round an infinity") |

1942 | n/a | return int(self._rescale(0, ROUND_FLOOR)) |

1943 | n/a | |

1944 | n/a | def __ceil__(self): |

1945 | n/a | """Return the ceiling of self, as an integer. |

1946 | n/a | |

1947 | n/a | For a finite Decimal instance self, return the least integer n |

1948 | n/a | such that n >= self. If self is infinite or a NaN then a |

1949 | n/a | Python exception is raised. |

1950 | n/a | |

1951 | n/a | """ |

1952 | n/a | if self._is_special: |

1953 | n/a | if self.is_nan(): |

1954 | n/a | raise ValueError("cannot round a NaN") |

1955 | n/a | else: |

1956 | n/a | raise OverflowError("cannot round an infinity") |

1957 | n/a | return int(self._rescale(0, ROUND_CEILING)) |

1958 | n/a | |

1959 | n/a | def fma(self, other, third, context=None): |

1960 | n/a | """Fused multiply-add. |

1961 | n/a | |

1962 | n/a | Returns self*other+third with no rounding of the intermediate |

1963 | n/a | product self*other. |

1964 | n/a | |

1965 | n/a | self and other are multiplied together, with no rounding of |

1966 | n/a | the result. The third operand is then added to the result, |

1967 | n/a | and a single final rounding is performed. |

1968 | n/a | """ |

1969 | n/a | |

1970 | n/a | other = _convert_other(other, raiseit=True) |

1971 | n/a | third = _convert_other(third, raiseit=True) |

1972 | n/a | |

1973 | n/a | # compute product; raise InvalidOperation if either operand is |

1974 | n/a | # a signaling NaN or if the product is zero times infinity. |

1975 | n/a | if self._is_special or other._is_special: |

1976 | n/a | if context is None: |

1977 | n/a | context = getcontext() |

1978 | n/a | if self._exp == 'N': |

1979 | n/a | return context._raise_error(InvalidOperation, 'sNaN', self) |

1980 | n/a | if other._exp == 'N': |

1981 | n/a | return context._raise_error(InvalidOperation, 'sNaN', other) |

1982 | n/a | if self._exp == 'n': |

1983 | n/a | product = self |

1984 | n/a | elif other._exp == 'n': |

1985 | n/a | product = other |

1986 | n/a | elif self._exp == 'F': |

1987 | n/a | if not other: |

1988 | n/a | return context._raise_error(InvalidOperation, |

1989 | n/a | 'INF * 0 in fma') |

1990 | n/a | product = _SignedInfinity[self._sign ^ other._sign] |

1991 | n/a | elif other._exp == 'F': |

1992 | n/a | if not self: |

1993 | n/a | return context._raise_error(InvalidOperation, |

1994 | n/a | '0 * INF in fma') |

1995 | n/a | product = _SignedInfinity[self._sign ^ other._sign] |

1996 | n/a | else: |

1997 | n/a | product = _dec_from_triple(self._sign ^ other._sign, |

1998 | n/a | str(int(self._int) * int(other._int)), |

1999 | n/a | self._exp + other._exp) |

2000 | n/a | |

2001 | n/a | return product.__add__(third, context) |

2002 | n/a | |

2003 | n/a | def _power_modulo(self, other, modulo, context=None): |

2004 | n/a | """Three argument version of __pow__""" |

2005 | n/a | |

2006 | n/a | other = _convert_other(other) |

2007 | n/a | if other is NotImplemented: |

2008 | n/a | return other |

2009 | n/a | modulo = _convert_other(modulo) |

2010 | n/a | if modulo is NotImplemented: |

2011 | n/a | return modulo |

2012 | n/a | |

2013 | n/a | if context is None: |

2014 | n/a | context = getcontext() |

2015 | n/a | |

2016 | n/a | # deal with NaNs: if there are any sNaNs then first one wins, |

2017 | n/a | # (i.e. behaviour for NaNs is identical to that of fma) |

2018 | n/a | self_is_nan = self._isnan() |

2019 | n/a | other_is_nan = other._isnan() |

2020 | n/a | modulo_is_nan = modulo._isnan() |

2021 | n/a | if self_is_nan or other_is_nan or modulo_is_nan: |

2022 | n/a | if self_is_nan == 2: |

2023 | n/a | return context._raise_error(InvalidOperation, 'sNaN', |

2024 | n/a | self) |

2025 | n/a | if other_is_nan == 2: |

2026 | n/a | return context._raise_error(InvalidOperation, 'sNaN', |

2027 | n/a | other) |

2028 | n/a | if modulo_is_nan == 2: |

2029 | n/a | return context._raise_error(InvalidOperation, 'sNaN', |

2030 | n/a | modulo) |

2031 | n/a | if self_is_nan: |

2032 | n/a | return self._fix_nan(context) |

2033 | n/a | if other_is_nan: |

2034 | n/a | return other._fix_nan(context) |

2035 | n/a | return modulo._fix_nan(context) |

2036 | n/a | |

2037 | n/a | # check inputs: we apply same restrictions as Python's pow() |

2038 | n/a | if not (self._isinteger() and |

2039 | n/a | other._isinteger() and |

2040 | n/a | modulo._isinteger()): |

2041 | n/a | return context._raise_error(InvalidOperation, |

2042 | n/a | 'pow() 3rd argument not allowed ' |

2043 | n/a | 'unless all arguments are integers') |

2044 | n/a | if other < 0: |

2045 | n/a | return context._raise_error(InvalidOperation, |

2046 | n/a | 'pow() 2nd argument cannot be ' |

2047 | n/a | 'negative when 3rd argument specified') |

2048 | n/a | if not modulo: |

2049 | n/a | return context._raise_error(InvalidOperation, |

2050 | n/a | 'pow() 3rd argument cannot be 0') |

2051 | n/a | |

2052 | n/a | # additional restriction for decimal: the modulus must be less |

2053 | n/a | # than 10**prec in absolute value |

2054 | n/a | if modulo.adjusted() >= context.prec: |

2055 | n/a | return context._raise_error(InvalidOperation, |

2056 | n/a | 'insufficient precision: pow() 3rd ' |

2057 | n/a | 'argument must not have more than ' |

2058 | n/a | 'precision digits') |

2059 | n/a | |

2060 | n/a | # define 0**0 == NaN, for consistency with two-argument pow |

2061 | n/a | # (even though it hurts!) |

2062 | n/a | if not other and not self: |

2063 | n/a | return context._raise_error(InvalidOperation, |

2064 | n/a | 'at least one of pow() 1st argument ' |

2065 | n/a | 'and 2nd argument must be nonzero ;' |

2066 | n/a | '0**0 is not defined') |

2067 | n/a | |

2068 | n/a | # compute sign of result |

2069 | n/a | if other._iseven(): |

2070 | n/a | sign = 0 |

2071 | n/a | else: |

2072 | n/a | sign = self._sign |

2073 | n/a | |

2074 | n/a | # convert modulo to a Python integer, and self and other to |

2075 | n/a | # Decimal integers (i.e. force their exponents to be >= 0) |

2076 | n/a | modulo = abs(int(modulo)) |

2077 | n/a | base = _WorkRep(self.to_integral_value()) |

2078 | n/a | exponent = _WorkRep(other.to_integral_value()) |

2079 | n/a | |

2080 | n/a | # compute result using integer pow() |

2081 | n/a | base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo |

2082 | n/a | for i in range(exponent.exp): |

2083 | n/a | base = pow(base, 10, modulo) |

2084 | n/a | base = pow(base, exponent.int, modulo) |

2085 | n/a | |

2086 | n/a | return _dec_from_triple(sign, str(base), 0) |

2087 | n/a | |

2088 | n/a | def _power_exact(self, other, p): |

2089 | n/a | """Attempt to compute self**other exactly. |

2090 | n/a | |

2091 | n/a | Given Decimals self and other and an integer p, attempt to |

2092 | n/a | compute an exact result for the power self**other, with p |

2093 | n/a | digits of precision. Return None if self**other is not |

2094 | n/a | exactly representable in p digits. |

2095 | n/a | |

2096 | n/a | Assumes that elimination of special cases has already been |

2097 | n/a | performed: self and other must both be nonspecial; self must |

2098 | n/a | be positive and not numerically equal to 1; other must be |

2099 | n/a | nonzero. For efficiency, other._exp should not be too large, |

2100 | n/a | so that 10**abs(other._exp) is a feasible calculation.""" |

2101 | n/a | |

2102 | n/a | # In the comments below, we write x for the value of self and y for the |

2103 | n/a | # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc |

2104 | n/a | # and yc positive integers not divisible by 10. |

2105 | n/a | |

2106 | n/a | # The main purpose of this method is to identify the *failure* |

2107 | n/a | # of x**y to be exactly representable with as little effort as |

2108 | n/a | # possible. So we look for cheap and easy tests that |

2109 | n/a | # eliminate the possibility of x**y being exact. Only if all |

2110 | n/a | # these tests are passed do we go on to actually compute x**y. |

2111 | n/a | |

2112 | n/a | # Here's the main idea. Express y as a rational number m/n, with m and |

2113 | n/a | # n relatively prime and n>0. Then for x**y to be exactly |

2114 | n/a | # representable (at *any* precision), xc must be the nth power of a |

2115 | n/a | # positive integer and xe must be divisible by n. If y is negative |

2116 | n/a | # then additionally xc must be a power of either 2 or 5, hence a power |

2117 | n/a | # of 2**n or 5**n. |

2118 | n/a | # |

2119 | n/a | # There's a limit to how small |y| can be: if y=m/n as above |

2120 | n/a | # then: |

2121 | n/a | # |

2122 | n/a | # (1) if xc != 1 then for the result to be representable we |

2123 | n/a | # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So |

2124 | n/a | # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <= |

2125 | n/a | # 2**(1/|y|), hence xc**|y| < 2 and the result is not |

2126 | n/a | # representable. |

2127 | n/a | # |

2128 | n/a | # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if |

2129 | n/a | # |y| < 1/|xe| then the result is not representable. |

2130 | n/a | # |

2131 | n/a | # Note that since x is not equal to 1, at least one of (1) and |

2132 | n/a | # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) < |

2133 | n/a | # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye. |

2134 | n/a | # |

2135 | n/a | # There's also a limit to how large y can be, at least if it's |

2136 | n/a | # positive: the normalized result will have coefficient xc**y, |

2137 | n/a | # so if it's representable then xc**y < 10**p, and y < |

2138 | n/a | # p/log10(xc). Hence if y*log10(xc) >= p then the result is |

2139 | n/a | # not exactly representable. |

2140 | n/a | |

2141 | n/a | # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye, |

2142 | n/a | # so |y| < 1/xe and the result is not representable. |

2143 | n/a | # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y| |

2144 | n/a | # < 1/nbits(xc). |

2145 | n/a | |

2146 | n/a | x = _WorkRep(self) |

2147 | n/a | xc, xe = x.int, x.exp |

2148 | n/a | while xc % 10 == 0: |

2149 | n/a | xc //= 10 |

2150 | n/a | xe += 1 |

2151 | n/a | |

2152 | n/a | y = _WorkRep(other) |

2153 | n/a | yc, ye = y.int, y.exp |

2154 | n/a | while yc % 10 == 0: |

2155 | n/a | yc //= 10 |

2156 | n/a | ye += 1 |

2157 | n/a | |

2158 | n/a | # case where xc == 1: result is 10**(xe*y), with xe*y |

2159 | n/a | # required to be an integer |

2160 | n/a | if xc == 1: |

2161 | n/a | xe *= yc |

2162 | n/a | # result is now 10**(xe * 10**ye); xe * 10**ye must be integral |

2163 | n/a | while xe % 10 == 0: |

2164 | n/a | xe //= 10 |

2165 | n/a | ye += 1 |

2166 | n/a | if ye < 0: |

2167 | n/a | return None |

2168 | n/a | exponent = xe * 10**ye |

2169 | n/a | if y.sign == 1: |

2170 | n/a | exponent = -exponent |

2171 | n/a | # if other is a nonnegative integer, use ideal exponent |

2172 | n/a | if other._isinteger() and other._sign == 0: |

2173 | n/a | ideal_exponent = self._exp*int(other) |

2174 | n/a | zeros = min(exponent-ideal_exponent, p-1) |

2175 | n/a | else: |

2176 | n/a | zeros = 0 |

2177 | n/a | return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros) |

2178 | n/a | |

2179 | n/a | # case where y is negative: xc must be either a power |

2180 | n/a | # of 2 or a power of 5. |

2181 | n/a | if y.sign == 1: |

2182 | n/a | last_digit = xc % 10 |

2183 | n/a | if last_digit in (2,4,6,8): |

2184 | n/a | # quick test for power of 2 |

2185 | n/a | if xc & -xc != xc: |

2186 | n/a | return None |

2187 | n/a | # now xc is a power of 2; e is its exponent |

2188 | n/a | e = _nbits(xc)-1 |

2189 | n/a | |

2190 | n/a | # We now have: |

2191 | n/a | # |

2192 | n/a | # x = 2**e * 10**xe, e > 0, and y < 0. |

2193 | n/a | # |

2194 | n/a | # The exact result is: |

2195 | n/a | # |

2196 | n/a | # x**y = 5**(-e*y) * 10**(e*y + xe*y) |

2197 | n/a | # |

2198 | n/a | # provided that both e*y and xe*y are integers. Note that if |

2199 | n/a | # 5**(-e*y) >= 10**p, then the result can't be expressed |

2200 | n/a | # exactly with p digits of precision. |

2201 | n/a | # |

2202 | n/a | # Using the above, we can guard against large values of ye. |

2203 | n/a | # 93/65 is an upper bound for log(10)/log(5), so if |

2204 | n/a | # |

2205 | n/a | # ye >= len(str(93*p//65)) |

2206 | n/a | # |

2207 | n/a | # then |

2208 | n/a | # |

2209 | n/a | # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5), |

2210 | n/a | # |

2211 | n/a | # so 5**(-e*y) >= 10**p, and the coefficient of the result |

2212 | n/a | # can't be expressed in p digits. |

2213 | n/a | |

2214 | n/a | # emax >= largest e such that 5**e < 10**p. |

2215 | n/a | emax = p*93//65 |

2216 | n/a | if ye >= len(str(emax)): |

2217 | n/a | return None |

2218 | n/a | |

2219 | n/a | # Find -e*y and -xe*y; both must be integers |

2220 | n/a | e = _decimal_lshift_exact(e * yc, ye) |

2221 | n/a | xe = _decimal_lshift_exact(xe * yc, ye) |

2222 | n/a | if e is None or xe is None: |

2223 | n/a | return None |

2224 | n/a | |

2225 | n/a | if e > emax: |

2226 | n/a | return None |

2227 | n/a | xc = 5**e |

2228 | n/a | |

2229 | n/a | elif last_digit == 5: |

2230 | n/a | # e >= log_5(xc) if xc is a power of 5; we have |

2231 | n/a | # equality all the way up to xc=5**2658 |

2232 | n/a | e = _nbits(xc)*28//65 |

2233 | n/a | xc, remainder = divmod(5**e, xc) |

2234 | n/a | if remainder: |

2235 | n/a | return None |

2236 | n/a | while xc % 5 == 0: |

2237 | n/a | xc //= 5 |

2238 | n/a | e -= 1 |

2239 | n/a | |

2240 | n/a | # Guard against large values of ye, using the same logic as in |

2241 | n/a | # the 'xc is a power of 2' branch. 10/3 is an upper bound for |

2242 | n/a | # log(10)/log(2). |

2243 | n/a | emax = p*10//3 |

2244 | n/a | if ye >= len(str(emax)): |

2245 | n/a | return None |

2246 | n/a | |

2247 | n/a | e = _decimal_lshift_exact(e * yc, ye) |

2248 | n/a | xe = _decimal_lshift_exact(xe * yc, ye) |

2249 | n/a | if e is None or xe is None: |

2250 | n/a | return None |

2251 | n/a | |

2252 | n/a | if e > emax: |

2253 | n/a | return None |

2254 | n/a | xc = 2**e |

2255 | n/a | else: |

2256 | n/a | return None |

2257 | n/a | |

2258 | n/a | if xc >= 10**p: |

2259 | n/a | return None |

2260 | n/a | xe = -e-xe |

2261 | n/a | return _dec_from_triple(0, str(xc), xe) |

2262 | n/a | |

2263 | n/a | # now y is positive; find m and n such that y = m/n |

2264 | n/a | if ye >= 0: |

2265 | n/a | m, n = yc*10**ye, 1 |

2266 | n/a | else: |

2267 | n/a | if xe != 0 and len(str(abs(yc*xe))) <= -ye: |

2268 | n/a | return None |

2269 | n/a | xc_bits = _nbits(xc) |

2270 | n/a | if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye: |

2271 | n/a | return None |

2272 | n/a | m, n = yc, 10**(-ye) |

2273 | n/a | while m % 2 == n % 2 == 0: |

2274 | n/a | m //= 2 |

2275 | n/a | n //= 2 |

2276 | n/a | while m % 5 == n % 5 == 0: |

2277 | n/a | m //= 5 |

2278 | n/a | n //= 5 |

2279 | n/a | |

2280 | n/a | # compute nth root of xc*10**xe |

2281 | n/a | if n > 1: |

2282 | n/a | # if 1 < xc < 2**n then xc isn't an nth power |

2283 | n/a | if xc != 1 and xc_bits <= n: |

2284 | n/a | return None |

2285 | n/a | |

2286 | n/a | xe, rem = divmod(xe, n) |

2287 | n/a | if rem != 0: |

2288 | n/a | return None |

2289 | n/a | |

2290 | n/a | # compute nth root of xc using Newton's method |

2291 | n/a | a = 1 << -(-_nbits(xc)//n) # initial estimate |

2292 | n/a | while True: |

2293 | n/a | q, r = divmod(xc, a**(n-1)) |

2294 | n/a | if a <= q: |

2295 | n/a | break |

2296 | n/a | else: |

2297 | n/a | a = (a*(n-1) + q)//n |

2298 | n/a | if not (a == q and r == 0): |

2299 | n/a | return None |

2300 | n/a | xc = a |

2301 | n/a | |

2302 | n/a | # now xc*10**xe is the nth root of the original xc*10**xe |

2303 | n/a | # compute mth power of xc*10**xe |

2304 | n/a | |

2305 | n/a | # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m > |

2306 | n/a | # 10**p and the result is not representable. |

2307 | n/a | if xc > 1 and m > p*100//_log10_lb(xc): |

2308 | n/a | return None |

2309 | n/a | xc = xc**m |

2310 | n/a | xe *= m |

2311 | n/a | if xc > 10**p: |

2312 | n/a | return None |

2313 | n/a | |

2314 | n/a | # by this point the result *is* exactly representable |

2315 | n/a | # adjust the exponent to get as close as possible to the ideal |

2316 | n/a | # exponent, if necessary |

2317 | n/a | str_xc = str(xc) |

2318 | n/a | if other._isinteger() and other._sign == 0: |

2319 | n/a | ideal_exponent = self._exp*int(other) |

2320 | n/a | zeros = min(xe-ideal_exponent, p-len(str_xc)) |

2321 | n/a | else: |

2322 | n/a | zeros = 0 |

2323 | n/a | return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros) |

2324 | n/a | |

2325 | n/a | def __pow__(self, other, modulo=None, context=None): |

2326 | n/a | """Return self ** other [ % modulo]. |

2327 | n/a | |

2328 | n/a | With two arguments, compute self**other. |

2329 | n/a | |

2330 | n/a | With three arguments, compute (self**other) % modulo. For the |

2331 | n/a | three argument form, the following restrictions on the |

2332 | n/a | arguments hold: |

2333 | n/a | |

2334 | n/a | - all three arguments must be integral |

2335 | n/a | - other must be nonnegative |

2336 | n/a | - either self or other (or both) must be nonzero |

2337 | n/a | - modulo must be nonzero and must have at most p digits, |

2338 | n/a | where p is the context precision. |

2339 | n/a | |

2340 | n/a | If any of these restrictions is violated the InvalidOperation |

2341 | n/a | flag is raised. |

2342 | n/a | |

2343 | n/a | The result of pow(self, other, modulo) is identical to the |

2344 | n/a | result that would be obtained by computing (self**other) % |

2345 | n/a | modulo with unbounded precision, but is computed more |

2346 | n/a | efficiently. It is always exact. |

2347 | n/a | """ |

2348 | n/a | |

2349 | n/a | if modulo is not None: |

2350 | n/a | return self._power_modulo(other, modulo, context) |

2351 | n/a | |

2352 | n/a | other = _convert_other(other) |

2353 | n/a | if other is NotImplemented: |

2354 | n/a | return other |

2355 | n/a | |

2356 | n/a | if context is None: |

2357 | n/a | context = getcontext() |

2358 | n/a | |

2359 | n/a | # either argument is a NaN => result is NaN |

2360 | n/a | ans = self._check_nans(other, context) |

2361 | n/a | if ans: |

2362 | n/a | return ans |

2363 | n/a | |

2364 | n/a | # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) |

2365 | n/a | if not other: |

2366 | n/a | if not self: |

2367 | n/a | return context._raise_error(InvalidOperation, '0 ** 0') |

2368 | n/a | else: |

2369 | n/a | return _One |

2370 | n/a | |

2371 | n/a | # result has sign 1 iff self._sign is 1 and other is an odd integer |

2372 | n/a | result_sign = 0 |

2373 | n/a | if self._sign == 1: |

2374 | n/a | if other._isinteger(): |

2375 | n/a | if not other._iseven(): |

2376 | n/a | result_sign = 1 |

2377 | n/a | else: |

2378 | n/a | # -ve**noninteger = NaN |

2379 | n/a | # (-0)**noninteger = 0**noninteger |

2380 | n/a | if self: |

2381 | n/a | return context._raise_error(InvalidOperation, |

2382 | n/a | 'x ** y with x negative and y not an integer') |

2383 | n/a | # negate self, without doing any unwanted rounding |

2384 | n/a | self = self.copy_negate() |

2385 | n/a | |

2386 | n/a | # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity |

2387 | n/a | if not self: |

2388 | n/a | if other._sign == 0: |

2389 | n/a | return _dec_from_triple(result_sign, '0', 0) |

2390 | n/a | else: |

2391 | n/a | return _SignedInfinity[result_sign] |

2392 | n/a | |

2393 | n/a | # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 |

2394 | n/a | if self._isinfinity(): |

2395 | n/a | if other._sign == 0: |

2396 | n/a | return _SignedInfinity[result_sign] |

2397 | n/a | else: |

2398 | n/a | return _dec_from_triple(result_sign, '0', 0) |

2399 | n/a | |

2400 | n/a | # 1**other = 1, but the choice of exponent and the flags |

2401 | n/a | # depend on the exponent of self, and on whether other is a |

2402 | n/a | # positive integer, a negative integer, or neither |

2403 | n/a | if self == _One: |

2404 | n/a | if other._isinteger(): |

2405 | n/a | # exp = max(self._exp*max(int(other), 0), |

2406 | n/a | # 1-context.prec) but evaluating int(other) directly |

2407 | n/a | # is dangerous until we know other is small (other |

2408 | n/a | # could be 1e999999999) |

2409 | n/a | if other._sign == 1: |

2410 | n/a | multiplier = 0 |

2411 | n/a | elif other > context.prec: |

2412 | n/a | multiplier = context.prec |

2413 | n/a | else: |

2414 | n/a | multiplier = int(other) |

2415 | n/a | |

2416 | n/a | exp = self._exp * multiplier |

2417 | n/a | if exp < 1-context.prec: |

2418 | n/a | exp = 1-context.prec |

2419 | n/a | context._raise_error(Rounded) |

2420 | n/a | else: |

2421 | n/a | context._raise_error(Inexact) |

2422 | n/a | context._raise_error(Rounded) |

2423 | n/a | exp = 1-context.prec |

2424 | n/a | |

2425 | n/a | return _dec_from_triple(result_sign, '1'+'0'*-exp, exp) |

2426 | n/a | |

2427 | n/a | # compute adjusted exponent of self |

2428 | n/a | self_adj = self.adjusted() |

2429 | n/a | |

2430 | n/a | # self ** infinity is infinity if self > 1, 0 if self < 1 |

2431 | n/a | # self ** -infinity is infinity if self < 1, 0 if self > 1 |

2432 | n/a | if other._isinfinity(): |

2433 | n/a | if (other._sign == 0) == (self_adj < 0): |

2434 | n/a | return _dec_from_triple(result_sign, '0', 0) |

2435 | n/a | else: |

2436 | n/a | return _SignedInfinity[result_sign] |

2437 | n/a | |

2438 | n/a | # from here on, the result always goes through the call |

2439 | n/a | # to _fix at the end of this function. |

2440 | n/a | ans = None |

2441 | n/a | exact = False |

2442 | n/a | |

2443 | n/a | # crude test to catch cases of extreme overflow/underflow. If |

2444 | n/a | # log10(self)*other >= 10**bound and bound >= len(str(Emax)) |

2445 | n/a | # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence |

2446 | n/a | # self**other >= 10**(Emax+1), so overflow occurs. The test |

2447 | n/a | # for underflow is similar. |

2448 | n/a | bound = self._log10_exp_bound() + other.adjusted() |

2449 | n/a | if (self_adj >= 0) == (other._sign == 0): |

2450 | n/a | # self > 1 and other +ve, or self < 1 and other -ve |

2451 | n/a | # possibility of overflow |

2452 | n/a | if bound >= len(str(context.Emax)): |

2453 | n/a | ans = _dec_from_triple(result_sign, '1', context.Emax+1) |

2454 | n/a | else: |

2455 | n/a | # self > 1 and other -ve, or self < 1 and other +ve |

2456 | n/a | # possibility of underflow to 0 |

2457 | n/a | Etiny = context.Etiny() |

2458 | n/a | if bound >= len(str(-Etiny)): |

2459 | n/a | ans = _dec_from_triple(result_sign, '1', Etiny-1) |

2460 | n/a | |

2461 | n/a | # try for an exact result with precision +1 |

2462 | n/a | if ans is None: |

2463 | n/a | ans = self._power_exact(other, context.prec + 1) |

2464 | n/a | if ans is not None: |

2465 | n/a | if result_sign == 1: |

2466 | n/a | ans = _dec_from_triple(1, ans._int, ans._exp) |

2467 | n/a | exact = True |

2468 | n/a | |

2469 | n/a | # usual case: inexact result, x**y computed directly as exp(y*log(x)) |

2470 | n/a | if ans is None: |

2471 | n/a | p = context.prec |

2472 | n/a | x = _WorkRep(self) |

2473 | n/a | xc, xe = x.int, x.exp |

2474 | n/a | y = _WorkRep(other) |

2475 | n/a | yc, ye = y.int, y.exp |

2476 | n/a | if y.sign == 1: |

2477 | n/a | yc = -yc |

2478 | n/a | |

2479 | n/a | # compute correctly rounded result: start with precision +3, |

2480 | n/a | # then increase precision until result is unambiguously roundable |

2481 | n/a | extra = 3 |

2482 | n/a | while True: |

2483 | n/a | coeff, exp = _dpower(xc, xe, yc, ye, p+extra) |

2484 | n/a | if coeff % (5*10**(len(str(coeff))-p-1)): |

2485 | n/a | break |

2486 | n/a | extra += 3 |

2487 | n/a | |

2488 | n/a | ans = _dec_from_triple(result_sign, str(coeff), exp) |

2489 | n/a | |

2490 | n/a | # unlike exp, ln and log10, the power function respects the |

2491 | n/a | # rounding mode; no need to switch to ROUND_HALF_EVEN here |

2492 | n/a | |

2493 | n/a | # There's a difficulty here when 'other' is not an integer and |

2494 | n/a | # the result is exact. In this case, the specification |

2495 | n/a | # requires that the Inexact flag be raised (in spite of |

2496 | n/a | # exactness), but since the result is exact _fix won't do this |

2497 | n/a | # for us. (Correspondingly, the Underflow signal should also |

2498 | n/a | # be raised for subnormal results.) We can't directly raise |

2499 | n/a | # these signals either before or after calling _fix, since |

2500 | n/a | # that would violate the precedence for signals. So we wrap |

2501 | n/a | # the ._fix call in a temporary context, and reraise |

2502 | n/a | # afterwards. |

2503 | n/a | if exact and not other._isinteger(): |

2504 | n/a | # pad with zeros up to length context.prec+1 if necessary; this |

2505 | n/a | # ensures that the Rounded signal will be raised. |

2506 | n/a | if len(ans._int) <= context.prec: |

2507 | n/a | expdiff = context.prec + 1 - len(ans._int) |

2508 | n/a | ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, |

2509 | n/a | ans._exp-expdiff) |

2510 | n/a | |

2511 | n/a | # create a copy of the current context, with cleared flags/traps |

2512 | n/a | newcontext = context.copy() |

2513 | n/a | newcontext.clear_flags() |

2514 | n/a | for exception in _signals: |

2515 | n/a | newcontext.traps[exception] = 0 |

2516 | n/a | |

2517 | n/a | # round in the new context |

2518 | n/a | ans = ans._fix(newcontext) |

2519 | n/a | |

2520 | n/a | # raise Inexact, and if necessary, Underflow |

2521 | n/a | newcontext._raise_error(Inexact) |

2522 | n/a | if newcontext.flags[Subnormal]: |

2523 | n/a | newcontext._raise_error(Underflow) |

2524 | n/a | |

2525 | n/a | # propagate signals to the original context; _fix could |

2526 | n/a | # have raised any of Overflow, Underflow, Subnormal, |

2527 | n/a | # Inexact, Rounded, Clamped. Overflow needs the correct |

2528 | n/a | # arguments. Note that the order of the exceptions is |

2529 | n/a | # important here. |

2530 | n/a | if newcontext.flags[Overflow]: |

2531 | n/a | context._raise_error(Overflow, 'above Emax', ans._sign) |

2532 | n/a | for exception in Underflow, Subnormal, Inexact, Rounded, Clamped: |

2533 | n/a | if newcontext.flags[exception]: |

2534 | n/a | context._raise_error(exception) |

2535 | n/a | |

2536 | n/a | else: |

2537 | n/a | ans = ans._fix(context) |

2538 | n/a | |

2539 | n/a | return ans |

2540 | n/a | |

2541 | n/a | def __rpow__(self, other, context=None): |

2542 | n/a | """Swaps self/other and returns __pow__.""" |

2543 | n/a | other = _convert_other(other) |

2544 | n/a | if other is NotImplemented: |

2545 | n/a | return other |

2546 | n/a | return other.__pow__(self, context=context) |

2547 | n/a | |

2548 | n/a | def normalize(self, context=None): |

2549 | n/a | """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" |

2550 | n/a | |

2551 | n/a | if context is None: |

2552 | n/a | context = getcontext() |

2553 | n/a | |

2554 | n/a | if self._is_special: |

2555 | n/a | ans = self._check_nans(context=context) |

2556 | n/a | if ans: |

2557 | n/a | return ans |

2558 | n/a | |

2559 | n/a | dup = self._fix(context) |

2560 | n/a | if dup._isinfinity(): |

2561 | n/a | return dup |

2562 | n/a | |

2563 | n/a | if not dup: |

2564 | n/a | return _dec_from_triple(dup._sign, '0', 0) |

2565 | n/a | exp_max = [context.Emax, context.Etop()][context.clamp] |

2566 | n/a | end = len(dup._int) |

2567 | n/a | exp = dup._exp |

2568 | n/a | while dup._int[end-1] == '0' and exp < exp_max: |

2569 | n/a | exp += 1 |

2570 | n/a | end -= 1 |

2571 | n/a | return _dec_from_triple(dup._sign, dup._int[:end], exp) |

2572 | n/a | |

2573 | n/a | def quantize(self, exp, rounding=None, context=None): |

2574 | n/a | """Quantize self so its exponent is the same as that of exp. |

2575 | n/a | |

2576 | n/a | Similar to self._rescale(exp._exp) but with error checking. |

2577 | n/a | """ |

2578 | n/a | exp = _convert_other(exp, raiseit=True) |

2579 | n/a | |

2580 | n/a | if context is None: |

2581 | n/a | context = getcontext() |

2582 | n/a | if rounding is None: |

2583 | n/a | rounding = context.rounding |

2584 | n/a | |

2585 | n/a | if self._is_special or exp._is_special: |

2586 | n/a | ans = self._check_nans(exp, context) |

2587 | n/a | if ans: |

2588 | n/a | return ans |

2589 | n/a | |

2590 | n/a | if exp._isinfinity() or self._isinfinity(): |

2591 | n/a | if exp._isinfinity() and self._isinfinity(): |

2592 | n/a | return Decimal(self) # if both are inf, it is OK |

2593 | n/a | return context._raise_error(InvalidOperation, |

2594 | n/a | 'quantize with one INF') |

2595 | n/a | |

2596 | n/a | # exp._exp should be between Etiny and Emax |

2597 | n/a | if not (context.Etiny() <= exp._exp <= context.Emax): |

2598 | n/a | return context._raise_error(InvalidOperation, |

2599 | n/a | 'target exponent out of bounds in quantize') |

2600 | n/a | |

2601 | n/a | if not self: |

2602 | n/a | ans = _dec_from_triple(self._sign, '0', exp._exp) |

2603 | n/a | return ans._fix(context) |

2604 | n/a | |

2605 | n/a | self_adjusted = self.adjusted() |

2606 | n/a | if self_adjusted > context.Emax: |

2607 | n/a | return context._raise_error(InvalidOperation, |

2608 | n/a | 'exponent of quantize result too large for current context') |

2609 | n/a | if self_adjusted - exp._exp + 1 > context.prec: |

2610 | n/a | return context._raise_error(InvalidOperation, |

2611 | n/a | 'quantize result has too many digits for current context') |

2612 | n/a | |

2613 | n/a | ans = self._rescale(exp._exp, rounding) |

2614 | n/a | if ans.adjusted() > context.Emax: |

2615 | n/a | return context._raise_error(InvalidOperation, |

2616 | n/a | 'exponent of quantize result too large for current context') |

2617 | n/a | if len(ans._int) > context.prec: |

2618 | n/a | return context._raise_error(InvalidOperation, |

2619 | n/a | 'quantize result has too many digits for current context') |

2620 | n/a | |

2621 | n/a | # raise appropriate flags |

2622 | n/a | if ans and ans.adjusted() < context.Emin: |

2623 | n/a | context._raise_error(Subnormal) |

2624 | n/a | if ans._exp > self._exp: |

2625 | n/a | if ans != self: |

2626 | n/a | context._raise_error(Inexact) |

2627 | n/a | context._raise_error(Rounded) |

2628 | n/a | |

2629 | n/a | # call to fix takes care of any necessary folddown, and |

2630 | n/a | # signals Clamped if necessary |

2631 | n/a | ans = ans._fix(context) |

2632 | n/a | return ans |

2633 | n/a | |

2634 | n/a | def same_quantum(self, other, context=None): |

2635 | n/a | """Return True if self and other have the same exponent; otherwise |

2636 | n/a | return False. |

2637 | n/a | |

2638 | n/a | If either operand is a special value, the following rules are used: |

2639 | n/a | * return True if both operands are infinities |

2640 | n/a | * return True if both operands are NaNs |

2641 | n/a | * otherwise, return False. |

2642 | n/a | """ |

2643 | n/a | other = _convert_other(other, raiseit=True) |

2644 | n/a | if self._is_special or other._is_special: |

2645 | n/a | return (self.is_nan() and other.is_nan() or |

2646 | n/a | self.is_infinite() and other.is_infinite()) |

2647 | n/a | return self._exp == other._exp |

2648 | n/a | |

2649 | n/a | def _rescale(self, exp, rounding): |

2650 | n/a | """Rescale self so that the exponent is exp, either by padding with zeros |

2651 | n/a | or by truncating digits, using the given rounding mode. |

2652 | n/a | |

2653 | n/a | Specials are returned without change. This operation is |

2654 | n/a | quiet: it raises no flags, and uses no information from the |

2655 | n/a | context. |

2656 | n/a | |

2657 | n/a | exp = exp to scale to (an integer) |

2658 | n/a | rounding = rounding mode |

2659 | n/a | """ |

2660 | n/a | if self._is_special: |

2661 | n/a | return Decimal(self) |

2662 | n/a | if not self: |

2663 | n/a | return _dec_from_triple(self._sign, '0', exp) |

2664 | n/a | |

2665 | n/a | if self._exp >= exp: |

2666 | n/a | # pad answer with zeros if necessary |

2667 | n/a | return _dec_from_triple(self._sign, |

2668 | n/a | self._int + '0'*(self._exp - exp), exp) |

2669 | n/a | |

2670 | n/a | # too many digits; round and lose data. If self.adjusted() < |

2671 | n/a | # exp-1, replace self by 10**(exp-1) before rounding |

2672 | n/a | digits = len(self._int) + self._exp - exp |

2673 | n/a | if digits < 0: |

2674 | n/a | self = _dec_from_triple(self._sign, '1', exp-1) |

2675 | n/a | digits = 0 |

2676 | n/a | this_function = self._pick_rounding_function[rounding] |

2677 | n/a | changed = this_function(self, digits) |

2678 | n/a | coeff = self._int[:digits] or '0' |

2679 | n/a | if changed == 1: |

2680 | n/a | coeff = str(int(coeff)+1) |

2681 | n/a | return _dec_from_triple(self._sign, coeff, exp) |

2682 | n/a | |

2683 | n/a | def _round(self, places, rounding): |

2684 | n/a | """Round a nonzero, nonspecial Decimal to a fixed number of |

2685 | n/a | significant figures, using the given rounding mode. |

2686 | n/a | |

2687 | n/a | Infinities, NaNs and zeros are returned unaltered. |

2688 | n/a | |

2689 | n/a | This operation is quiet: it raises no flags, and uses no |

2690 | n/a | information from the context. |

2691 | n/a | |

2692 | n/a | """ |

2693 | n/a | if places <= 0: |

2694 | n/a | raise ValueError("argument should be at least 1 in _round") |

2695 | n/a | if self._is_special or not self: |

2696 | n/a | return Decimal(self) |

2697 | n/a | ans = self._rescale(self.adjusted()+1-places, rounding) |

2698 | n/a | # it can happen that the rescale alters the adjusted exponent; |

2699 | n/a | # for example when rounding 99.97 to 3 significant figures. |

2700 | n/a | # When this happens we end up with an extra 0 at the end of |

2701 | n/a | # the number; a second rescale fixes this. |

2702 | n/a | if ans.adjusted() != self.adjusted(): |

2703 | n/a | ans = ans._rescale(ans.adjusted()+1-places, rounding) |

2704 | n/a | return ans |

2705 | n/a | |

2706 | n/a | def to_integral_exact(self, rounding=None, context=None): |

2707 | n/a | """Rounds to a nearby integer. |

2708 | n/a | |

2709 | n/a | If no rounding mode is specified, take the rounding mode from |

2710 | n/a | the context. This method raises the Rounded and Inexact flags |

2711 | n/a | when appropriate. |

2712 | n/a | |

2713 | n/a | See also: to_integral_value, which does exactly the same as |

2714 | n/a | this method except that it doesn't raise Inexact or Rounded. |

2715 | n/a | """ |

2716 | n/a | if self._is_special: |

2717 | n/a | ans = self._check_nans(context=context) |

2718 | n/a | if ans: |

2719 | n/a | return ans |

2720 | n/a | return Decimal(self) |

2721 | n/a | if self._exp >= 0: |

2722 | n/a | return Decimal(self) |

2723 | n/a | if not self: |

2724 | n/a | return _dec_from_triple(self._sign, '0', 0) |

2725 | n/a | if context is None: |

2726 | n/a | context = getcontext() |

2727 | n/a | if rounding is None: |

2728 | n/a | rounding = context.rounding |

2729 | n/a | ans = self._rescale(0, rounding) |

2730 | n/a | if ans != self: |

2731 | n/a | context._raise_error(Inexact) |

2732 | n/a | context._raise_error(Rounded) |

2733 | n/a | return ans |

2734 | n/a | |

2735 | n/a | def to_integral_value(self, rounding=None, context=None): |

2736 | n/a | """Rounds to the nearest integer, without raising inexact, rounded.""" |

2737 | n/a | if context is None: |

2738 | n/a | context = getcontext() |

2739 | n/a | if rounding is None: |

2740 | n/a | rounding = context.rounding |

2741 | n/a | if self._is_special: |

2742 | n/a | ans = self._check_nans(context=context) |

2743 | n/a | if ans: |

2744 | n/a | return ans |

2745 | n/a | return Decimal(self) |

2746 | n/a | if self._exp >= 0: |

2747 | n/a | return Decimal(self) |

2748 | n/a | else: |

2749 | n/a | return self._rescale(0, rounding) |

2750 | n/a | |

2751 | n/a | # the method name changed, but we provide also the old one, for compatibility |

2752 | n/a | to_integral = to_integral_value |

2753 | n/a | |

2754 | n/a | def sqrt(self, context=None): |

2755 | n/a | """Return the square root of self.""" |

2756 | n/a | if context is None: |

2757 | n/a | context = getcontext() |

2758 | n/a | |

2759 | n/a | if self._is_special: |

2760 | n/a | ans = self._check_nans(context=context) |

2761 | n/a | if ans: |

2762 | n/a | return ans |

2763 | n/a | |

2764 | n/a | if self._isinfinity() and self._sign == 0: |

2765 | n/a | return Decimal(self) |

2766 | n/a | |

2767 | n/a | if not self: |

2768 | n/a | # exponent = self._exp // 2. sqrt(-0) = -0 |

2769 | n/a | ans = _dec_from_triple(self._sign, '0', self._exp // 2) |

2770 | n/a | return ans._fix(context) |

2771 | n/a | |

2772 | n/a | if self._sign == 1: |

2773 | n/a | return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') |

2774 | n/a | |

2775 | n/a | # At this point self represents a positive number. Let p be |

2776 | n/a | # the desired precision and express self in the form c*100**e |

2777 | n/a | # with c a positive real number and e an integer, c and e |

2778 | n/a | # being chosen so that 100**(p-1) <= c < 100**p. Then the |

2779 | n/a | # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1) |

2780 | n/a | # <= sqrt(c) < 10**p, so the closest representable Decimal at |

2781 | n/a | # precision p is n*10**e where n = round_half_even(sqrt(c)), |

2782 | n/a | # the closest integer to sqrt(c) with the even integer chosen |

2783 | n/a | # in the case of a tie. |

2784 | n/a | # |

2785 | n/a | # To ensure correct rounding in all cases, we use the |

2786 | n/a | # following trick: we compute the square root to an extra |

2787 | n/a | # place (precision p+1 instead of precision p), rounding down. |

2788 | n/a | # Then, if the result is inexact and its last digit is 0 or 5, |

2789 | n/a | # we increase the last digit to 1 or 6 respectively; if it's |

2790 | n/a | # exact we leave the last digit alone. Now the final round to |

2791 | n/a | # p places (or fewer in the case of underflow) will round |

2792 | n/a | # correctly and raise the appropriate flags. |

2793 | n/a | |

2794 | n/a | # use an extra digit of precision |

2795 | n/a | prec = context.prec+1 |

2796 | n/a | |

2797 | n/a | # write argument in the form c*100**e where e = self._exp//2 |

2798 | n/a | # is the 'ideal' exponent, to be used if the square root is |

2799 | n/a | # exactly representable. l is the number of 'digits' of c in |

2800 | n/a | # base 100, so that 100**(l-1) <= c < 100**l. |

2801 | n/a | op = _WorkRep(self) |

2802 | n/a | e = op.exp >> 1 |

2803 | n/a | if op.exp & 1: |

2804 | n/a | c = op.int * 10 |

2805 | n/a | l = (len(self._int) >> 1) + 1 |

2806 | n/a | else: |

2807 | n/a | c = op.int |

2808 | n/a | l = len(self._int)+1 >> 1 |

2809 | n/a | |

2810 | n/a | # rescale so that c has exactly prec base 100 'digits' |

2811 | n/a | shift = prec-l |

2812 | n/a | if shift >= 0: |

2813 | n/a | c *= 100**shift |

2814 | n/a | exact = True |

2815 | n/a | else: |

2816 | n/a | c, remainder = divmod(c, 100**-shift) |

2817 | n/a | exact = not remainder |

2818 | n/a | e -= shift |

2819 | n/a | |

2820 | n/a | # find n = floor(sqrt(c)) using Newton's method |

2821 | n/a | n = 10**prec |

2822 | n/a | while True: |

2823 | n/a | q = c//n |

2824 | n/a | if n <= q: |

2825 | n/a | break |

2826 | n/a | else: |

2827 | n/a | n = n + q >> 1 |

2828 | n/a | exact = exact and n*n == c |

2829 | n/a | |

2830 | n/a | if exact: |

2831 | n/a | # result is exact; rescale to use ideal exponent e |

2832 | n/a | if shift >= 0: |

2833 | n/a | # assert n % 10**shift == 0 |

2834 | n/a | n //= 10**shift |

2835 | n/a | else: |

2836 | n/a | n *= 10**-shift |

2837 | n/a | e += shift |

2838 | n/a | else: |

2839 | n/a | # result is not exact; fix last digit as described above |

2840 | n/a | if n % 5 == 0: |

2841 | n/a | n += 1 |

2842 | n/a | |

2843 | n/a | ans = _dec_from_triple(0, str(n), e) |

2844 | n/a | |

2845 | n/a | # round, and fit to current context |

2846 | n/a | context = context._shallow_copy() |

2847 | n/a | rounding = context._set_rounding(ROUND_HALF_EVEN) |

2848 | n/a | ans = ans._fix(context) |

2849 | n/a | context.rounding = rounding |

2850 | n/a | |

2851 | n/a | return ans |

2852 | n/a | |

2853 | n/a | def max(self, other, context=None): |

2854 | n/a | """Returns the larger value. |

2855 | n/a | |

2856 | n/a | Like max(self, other) except if one is not a number, returns |

2857 | n/a | NaN (and signals if one is sNaN). Also rounds. |

2858 | n/a | """ |

2859 | n/a | other = _convert_other(other, raiseit=True) |

2860 | n/a | |

2861 | n/a | if context is None: |

2862 | n/a | context = getcontext() |

2863 | n/a | |

2864 | n/a | if self._is_special or other._is_special: |

2865 | n/a | # If one operand is a quiet NaN and the other is number, then the |

2866 | n/a | # number is always returned |

2867 | n/a | sn = self._isnan() |

2868 | n/a | on = other._isnan() |

2869 | n/a | if sn or on: |

2870 | n/a | if on == 1 and sn == 0: |

2871 | n/a | return self._fix(context) |

2872 | n/a | if sn == 1 and on == 0: |

2873 | n/a | return other._fix(context) |

2874 | n/a | return self._check_nans(other, context) |

2875 | n/a | |

2876 | n/a | c = self._cmp(other) |

2877 | n/a | if c == 0: |

2878 | n/a | # If both operands are finite and equal in numerical value |

2879 | n/a | # then an ordering is applied: |

2880 | n/a | # |

2881 | n/a | # If the signs differ then max returns the operand with the |

2882 | n/a | # positive sign and min returns the operand with the negative sign |

2883 | n/a | # |

2884 | n/a | # If the signs are the same then the exponent is used to select |

2885 | n/a | # the result. This is exactly the ordering used in compare_total. |

2886 | n/a | c = self.compare_total(other) |

2887 | n/a | |

2888 | n/a | if c == -1: |

2889 | n/a | ans = other |

2890 | n/a | else: |

2891 | n/a | ans = self |

2892 | n/a | |

2893 | n/a | return ans._fix(context) |

2894 | n/a | |

2895 | n/a | def min(self, other, context=None): |

2896 | n/a | """Returns the smaller value. |

2897 | n/a | |

2898 | n/a | Like min(self, other) except if one is not a number, returns |

2899 | n/a | NaN (and signals if one is sNaN). Also rounds. |

2900 | n/a | """ |

2901 | n/a | other = _convert_other(other, raiseit=True) |

2902 | n/a | |

2903 | n/a | if context is None: |

2904 | n/a | context = getcontext() |

2905 | n/a | |

2906 | n/a | if self._is_special or other._is_special: |

2907 | n/a | # If one operand is a quiet NaN and the other is number, then the |

2908 | n/a | # number is always returned |

2909 | n/a | sn = self._isnan() |

2910 | n/a | on = other._isnan() |

2911 | n/a | if sn or on: |

2912 | n/a | if on == 1 and sn == 0: |

2913 | n/a | return self._fix(context) |

2914 | n/a | if sn == 1 and on == 0: |

2915 | n/a | return other._fix(context) |

2916 | n/a | return self._check_nans(other, context) |

2917 | n/a | |

2918 | n/a | c = self._cmp(other) |

2919 | n/a | if c == 0: |

2920 | n/a | c = self.compare_total(other) |

2921 | n/a | |

2922 | n/a | if c == -1: |

2923 | n/a | ans = self |

2924 | n/a | else: |

2925 | n/a | ans = other |

2926 | n/a | |

2927 | n/a | return ans._fix(context) |

2928 | n/a | |

2929 | n/a | def _isinteger(self): |

2930 | n/a | """Returns whether self is an integer""" |

2931 | n/a | if self._is_special: |

2932 | n/a | return False |

2933 | n/a | if self._exp >= 0: |

2934 | n/a | return True |

2935 | n/a | rest = self._int[self._exp:] |

2936 | n/a | return rest == '0'*len(rest) |

2937 | n/a | |

2938 | n/a | def _iseven(self): |

2939 | n/a | """Returns True if self is even. Assumes self is an integer.""" |

2940 | n/a | if not self or self._exp > 0: |

2941 | n/a | return True |

2942 | n/a | return self._int[-1+self._exp] in '02468' |

2943 | n/a | |

2944 | n/a | def adjusted(self): |

2945 | n/a | """Return the adjusted exponent of self""" |

2946 | n/a | try: |

2947 | n/a | return self._exp + len(self._int) - 1 |

2948 | n/a | # If NaN or Infinity, self._exp is string |

2949 | n/a | except TypeError: |

2950 | n/a | return 0 |

2951 | n/a | |

2952 | n/a | def canonical(self): |

2953 | n/a | """Returns the same Decimal object. |

2954 | n/a | |

2955 | n/a | As we do not have different encodings for the same number, the |

2956 | n/a | received object already is in its canonical form. |

2957 | n/a | """ |

2958 | n/a | return self |

2959 | n/a | |

2960 | n/a | def compare_signal(self, other, context=None): |

2961 | n/a | """Compares self to the other operand numerically. |

2962 | n/a | |

2963 | n/a | It's pretty much like compare(), but all NaNs signal, with signaling |

2964 | n/a | NaNs taking precedence over quiet NaNs. |

2965 | n/a | """ |

2966 | n/a | other = _convert_other(other, raiseit = True) |

2967 | n/a | ans = self._compare_check_nans(other, context) |

2968 | n/a | if ans: |

2969 | n/a | return ans |

2970 | n/a | return self.compare(other, context=context) |

2971 | n/a | |

2972 | n/a | def compare_total(self, other, context=None): |

2973 | n/a | """Compares self to other using the abstract representations. |

2974 | n/a | |

2975 | n/a | This is not like the standard compare, which use their numerical |

2976 | n/a | value. Note that a total ordering is defined for all possible abstract |

2977 | n/a | representations. |

2978 | n/a | """ |

2979 | n/a | other = _convert_other(other, raiseit=True) |

2980 | n/a | |

2981 | n/a | # if one is negative and the other is positive, it's easy |

2982 | n/a | if self._sign and not other._sign: |

2983 | n/a | return _NegativeOne |

2984 | n/a | if not self._sign and other._sign: |

2985 | n/a | return _One |

2986 | n/a | sign = self._sign |

2987 | n/a | |

2988 | n/a | # let's handle both NaN types |

2989 | n/a | self_nan = self._isnan() |

2990 | n/a | other_nan = other._isnan() |

2991 | n/a | if self_nan or other_nan: |

2992 | n/a | if self_nan == other_nan: |

2993 | n/a | # compare payloads as though they're integers |

2994 | n/a | self_key = len(self._int), self._int |

2995 | n/a | other_key = len(other._int), other._int |

2996 | n/a | if self_key < other_key: |

2997 | n/a | if sign: |

2998 | n/a | return _One |

2999 | n/a | else: |

3000 | n/a | return _NegativeOne |

3001 | n/a | if self_key > other_key: |

3002 | n/a | if sign: |

3003 | n/a | return _NegativeOne |

3004 | n/a | else: |

3005 | n/a | return _One |

3006 | n/a | return _Zero |

3007 | n/a | |

3008 | n/a | if sign: |

3009 | n/a | if self_nan == 1: |

3010 | n/a | return _NegativeOne |

3011 | n/a | if other_nan == 1: |

3012 | n/a | return _One |

3013 | n/a | if self_nan == 2: |

3014 | n/a | return _NegativeOne |

3015 | n/a | if other_nan == 2: |

3016 | n/a | return _One |

3017 | n/a | else: |

3018 | n/a | if self_nan == 1: |

3019 | n/a | return _One |

3020 | n/a | if other_nan == 1: |

3021 | n/a | return _NegativeOne |

3022 | n/a | if self_nan == 2: |

3023 | n/a | return _One |

3024 | n/a | if other_nan == 2: |

3025 | n/a | return _NegativeOne |

3026 | n/a | |

3027 | n/a | if self < other: |

3028 | n/a | return _NegativeOne |

3029 | n/a | if self > other: |

3030 | n/a | return _One |

3031 | n/a | |

3032 | n/a | if self._exp < other._exp: |

3033 | n/a | if sign: |

3034 | n/a | return _One |

3035 | n/a | else: |

3036 | n/a | return _NegativeOne |

3037 | n/a | if self._exp > other._exp: |

3038 | n/a | if sign: |

3039 | n/a | return _NegativeOne |

3040 | n/a | else: |

3041 | n/a | return _One |

3042 | n/a | return _Zero |

3043 | n/a | |

3044 | n/a | |

3045 | n/a | def compare_total_mag(self, other, context=None): |

3046 | n/a | """Compares self to other using abstract repr., ignoring sign. |

3047 | n/a | |

3048 | n/a | Like compare_total, but with operand's sign ignored and assumed to be 0. |

3049 | n/a | """ |

3050 | n/a | other = _convert_other(other, raiseit=True) |

3051 | n/a | |

3052 | n/a | s = self.copy_abs() |

3053 | n/a | o = other.copy_abs() |

3054 | n/a | return s.compare_total(o) |

3055 | n/a | |

3056 | n/a | def copy_abs(self): |

3057 | n/a | """Returns a copy with the sign set to 0. """ |

3058 | n/a | return _dec_from_triple(0, self._int, self._exp, self._is_special) |

3059 | n/a | |

3060 | n/a | def copy_negate(self): |

3061 | n/a | """Returns a copy with the sign inverted.""" |

3062 | n/a | if self._sign: |

3063 | n/a | return _dec_from_triple(0, self._int, self._exp, self._is_special) |

3064 | n/a | else: |

3065 | n/a | return _dec_from_triple(1, self._int, self._exp, self._is_special) |

3066 | n/a | |

3067 | n/a | def copy_sign(self, other, context=None): |

3068 | n/a | """Returns self with the sign of other.""" |

3069 | n/a | other = _convert_other(other, raiseit=True) |

3070 | n/a | return _dec_from_triple(other._sign, self._int, |

3071 | n/a | self._exp, self._is_special) |

3072 | n/a | |

3073 | n/a | def exp(self, context=None): |

3074 | n/a | """Returns e ** self.""" |

3075 | n/a | |

3076 | n/a | if context is None: |

3077 | n/a | context = getcontext() |

3078 | n/a | |

3079 | n/a | # exp(NaN) = NaN |

3080 | n/a | ans = self._check_nans(context=context) |

3081 | n/a | if ans: |

3082 | n/a | return ans |

3083 | n/a | |

3084 | n/a | # exp(-Infinity) = 0 |

3085 | n/a | if self._isinfinity() == -1: |

3086 | n/a | return _Zero |

3087 | n/a | |

3088 | n/a | # exp(0) = 1 |

3089 | n/a | if not self: |

3090 | n/a | return _One |

3091 | n/a | |

3092 | n/a | # exp(Infinity) = Infinity |

3093 | n/a | if self._isinfinity() == 1: |

3094 | n/a | return Decimal(self) |

3095 | n/a | |

3096 | n/a | # the result is now guaranteed to be inexact (the true |

3097 | n/a | # mathematical result is transcendental). There's no need to |

3098 | n/a | # raise Rounded and Inexact here---they'll always be raised as |

3099 | n/a | # a result of the call to _fix. |

3100 | n/a | p = context.prec |

3101 | n/a | adj = self.adjusted() |

3102 | n/a | |

3103 | n/a | # we only need to do any computation for quite a small range |

3104 | n/a | # of adjusted exponents---for example, -29 <= adj <= 10 for |

3105 | n/a | # the default context. For smaller exponent the result is |

3106 | n/a | # indistinguishable from 1 at the given precision, while for |

3107 | n/a | # larger exponent the result either overflows or underflows. |

3108 | n/a | if self._sign == 0 and adj > len(str((context.Emax+1)*3)): |

3109 | n/a | # overflow |

3110 | n/a | ans = _dec_from_triple(0, '1', context.Emax+1) |

3111 | n/a | elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)): |

3112 | n/a | # underflow to 0 |

3113 | n/a | ans = _dec_from_triple(0, '1', context.Etiny()-1) |

3114 | n/a | elif self._sign == 0 and adj < -p: |

3115 | n/a | # p+1 digits; final round will raise correct flags |

3116 | n/a | ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p) |

3117 | n/a | elif self._sign == 1 and adj < -p-1: |

3118 | n/a | # p+1 digits; final round will raise correct flags |

3119 | n/a | ans = _dec_from_triple(0, '9'*(p+1), -p-1) |

3120 | n/a | # general case |

3121 | n/a | else: |

3122 | n/a | op = _WorkRep(self) |

3123 | n/a | c, e = op.int, op.exp |

3124 | n/a | if op.sign == 1: |

3125 | n/a | c = -c |

3126 | n/a | |

3127 | n/a | # compute correctly rounded result: increase precision by |

3128 | n/a | # 3 digits at a time until we get an unambiguously |

3129 | n/a | # roundable result |

3130 | n/a | extra = 3 |

3131 | n/a | while True: |

3132 | n/a | coeff, exp = _dexp(c, e, p+extra) |

3133 | n/a | if coeff % (5*10**(len(str(coeff))-p-1)): |

3134 | n/a | break |

3135 | n/a | extra += 3 |

3136 | n/a | |

3137 | n/a | ans = _dec_from_triple(0, str(coeff), exp) |

3138 | n/a | |

3139 | n/a | # at this stage, ans should round correctly with *any* |

3140 | n/a | # rounding mode, not just with ROUND_HALF_EVEN |

3141 | n/a | context = context._shallow_copy() |

3142 | n/a | rounding = context._set_rounding(ROUND_HALF_EVEN) |

3143 | n/a | ans = ans._fix(context) |

3144 | n/a | context.rounding = rounding |

3145 | n/a | |

3146 | n/a | return ans |

3147 | n/a | |

3148 | n/a | def is_canonical(self): |

3149 | n/a | """Return True if self is canonical; otherwise return False. |

3150 | n/a | |

3151 | n/a | Currently, the encoding of a Decimal instance is always |

3152 | n/a | canonical, so this method returns True for any Decimal. |

3153 | n/a | """ |

3154 | n/a | return True |

3155 | n/a | |

3156 | n/a | def is_finite(self): |

3157 | n/a | """Return True if self is finite; otherwise return False. |

3158 | n/a | |

3159 | n/a | A Decimal instance is considered finite if it is neither |

3160 | n/a | infinite nor a NaN. |

3161 | n/a | """ |

3162 | n/a | return not self._is_special |

3163 | n/a | |

3164 | n/a | def is_infinite(self): |

3165 | n/a | """Return True if self is infinite; otherwise return False.""" |

3166 | n/a | return self._exp == 'F' |

3167 | n/a | |

3168 | n/a | def is_nan(self): |

3169 | n/a | """Return True if self is a qNaN or sNaN; otherwise return False.""" |

3170 | n/a | return self._exp in ('n', 'N') |

3171 | n/a | |

3172 | n/a | def is_normal(self, context=None): |

3173 | n/a | """Return True if self is a normal number; otherwise return False.""" |

3174 | n/a | if self._is_special or not self: |

3175 | n/a | return False |

3176 | n/a | if context is None: |

3177 | n/a | context = getcontext() |

3178 | n/a | return context.Emin <= self.adjusted() |

3179 | n/a | |

3180 | n/a | def is_qnan(self): |

3181 | n/a | """Return True if self is a quiet NaN; otherwise return False.""" |

3182 | n/a | return self._exp == 'n' |

3183 | n/a | |

3184 | n/a | def is_signed(self): |

3185 | n/a | """Return True if self is negative; otherwise return False.""" |

3186 | n/a | return self._sign == 1 |

3187 | n/a | |

3188 | n/a | def is_snan(self): |

3189 | n/a | """Return True if self is a signaling NaN; otherwise return False.""" |

3190 | n/a | return self._exp == 'N' |

3191 | n/a | |

3192 | n/a | def is_subnormal(self, context=None): |

3193 | n/a | """Return True if self is subnormal; otherwise return False.""" |

3194 | n/a | if self._is_special or not self: |

3195 | n/a | return False |

3196 | n/a | if context is None: |

3197 | n/a | context = getcontext() |

3198 | n/a | return self.adjusted() < context.Emin |

3199 | n/a | |

3200 | n/a | def is_zero(self): |

3201 | n/a | """Return True if self is a zero; otherwise return False.""" |

3202 | n/a | return not self._is_special and self._int == '0' |

3203 | n/a | |

3204 | n/a | def _ln_exp_bound(self): |

3205 | n/a | """Compute a lower bound for the adjusted exponent of self.ln(). |

3206 | n/a | In other words, compute r such that self.ln() >= 10**r. Assumes |

3207 | n/a | that self is finite and positive and that self != 1. |

3208 | n/a | """ |

3209 | n/a | |

3210 | n/a | # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1 |

3211 | n/a | adj = self._exp + len(self._int) - 1 |

3212 | n/a | if adj >= 1: |

3213 | n/a | # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10) |

3214 | n/a | return len(str(adj*23//10)) - 1 |

3215 | n/a | if adj <= -2: |

3216 | n/a | # argument <= 0.1 |

3217 | n/a | return len(str((-1-adj)*23//10)) - 1 |

3218 | n/a | op = _WorkRep(self) |

3219 | n/a | c, e = op.int, op.exp |

3220 | n/a | if adj == 0: |

3221 | n/a | # 1 < self < 10 |

3222 | n/a | num = str(c-10**-e) |

3223 | n/a | den = str(c) |

3224 | n/a | return len(num) - len(den) - (num < den) |

3225 | n/a | # adj == -1, 0.1 <= self < 1 |

3226 | n/a | return e + len(str(10**-e - c)) - 1 |

3227 | n/a | |

3228 | n/a | |

3229 | n/a | def ln(self, context=None): |

3230 | n/a | """Returns the natural (base e) logarithm of self.""" |

3231 | n/a | |

3232 | n/a | if context is None: |

3233 | n/a | context = getcontext() |

3234 | n/a | |

3235 | n/a | # ln(NaN) = NaN |

3236 | n/a | ans = self._check_nans(context=context) |

3237 | n/a | if ans: |

3238 | n/a | return ans |

3239 | n/a | |

3240 | n/a | # ln(0.0) == -Infinity |

3241 | n/a | if not self: |

3242 | n/a | return _NegativeInfinity |

3243 | n/a | |

3244 | n/a | # ln(Infinity) = Infinity |

3245 | n/a | if self._isinfinity() == 1: |

3246 | n/a | return _Infinity |

3247 | n/a | |

3248 | n/a | # ln(1.0) == 0.0 |

3249 | n/a | if self == _One: |

3250 | n/a | return _Zero |

3251 | n/a | |

3252 | n/a | # ln(negative) raises InvalidOperation |

3253 | n/a | if self._sign == 1: |

3254 | n/a | return context._raise_error(InvalidOperation, |

3255 | n/a | 'ln of a negative value') |

3256 | n/a | |

3257 | n/a | # result is irrational, so necessarily inexact |

3258 | n/a | op = _WorkRep(self) |

3259 | n/a | c, e = op.int, op.exp |

3260 | n/a | p = context.prec |

3261 | n/a | |

3262 | n/a | # correctly rounded result: repeatedly increase precision by 3 |

3263 | n/a | # until we get an unambiguously roundable result |

3264 | n/a | places = p - self._ln_exp_bound() + 2 # at least p+3 places |

3265 | n/a | while True: |

3266 | n/a | coeff = _dlog(c, e, places) |

3267 | n/a | # assert len(str(abs(coeff)))-p >= 1 |

3268 | n/a | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |

3269 | n/a | break |

3270 | n/a | places += 3 |

3271 | n/a | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |

3272 | n/a | |

3273 | n/a | context = context._shallow_copy() |

3274 | n/a | rounding = context._set_rounding(ROUND_HALF_EVEN) |

3275 | n/a | ans = ans._fix(context) |

3276 | n/a | context.rounding = rounding |

3277 | n/a | return ans |

3278 | n/a | |

3279 | n/a | def _log10_exp_bound(self): |

3280 | n/a | """Compute a lower bound for the adjusted exponent of self.log10(). |

3281 | n/a | In other words, find r such that self.log10() >= 10**r. |

3282 | n/a | Assumes that self is finite and positive and that self != 1. |

3283 | n/a | """ |

3284 | n/a | |

3285 | n/a | # For x >= 10 or x < 0.1 we only need a bound on the integer |

3286 | n/a | # part of log10(self), and this comes directly from the |

3287 | n/a | # exponent of x. For 0.1 <= x <= 10 we use the inequalities |

3288 | n/a | # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > |

3289 | n/a | # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0 |

3290 | n/a | |

3291 | n/a | adj = self._exp + len(self._int) - 1 |

3292 | n/a | if adj >= 1: |

3293 | n/a | # self >= 10 |

3294 | n/a | return len(str(adj))-1 |

3295 | n/a | if adj <= -2: |

3296 | n/a | # self < 0.1 |

3297 | n/a | return len(str(-1-adj))-1 |

3298 | n/a | op = _WorkRep(self) |

3299 | n/a | c, e = op.int, op.exp |

3300 | n/a | if adj == 0: |

3301 | n/a | # 1 < self < 10 |

3302 | n/a | num = str(c-10**-e) |

3303 | n/a | den = str(231*c) |

3304 | n/a | return len(num) - len(den) - (num < den) + 2 |

3305 | n/a | # adj == -1, 0.1 <= self < 1 |

3306 | n/a | num = str(10**-e-c) |

3307 | n/a | return len(num) + e - (num < "231") - 1 |

3308 | n/a | |

3309 | n/a | def log10(self, context=None): |

3310 | n/a | """Returns the base 10 logarithm of self.""" |

3311 | n/a | |

3312 | n/a | if context is None: |

3313 | n/a | context = getcontext() |

3314 | n/a | |

3315 | n/a | # log10(NaN) = NaN |

3316 | n/a | ans = self._check_nans(context=context) |

3317 | n/a | if ans: |

3318 | n/a | return ans |

3319 | n/a | |

3320 | n/a | # log10(0.0) == -Infinity |

3321 | n/a | if not self: |

3322 | n/a | return _NegativeInfinity |

3323 | n/a | |

3324 | n/a | # log10(Infinity) = Infinity |

3325 | n/a | if self._isinfinity() == 1: |

3326 | n/a | return _Infinity |

3327 | n/a | |

3328 | n/a | # log10(negative or -Infinity) raises InvalidOperation |

3329 | n/a | if self._sign == 1: |

3330 | n/a | return context._raise_error(InvalidOperation, |

3331 | n/a | 'log10 of a negative value') |

3332 | n/a | |

3333 | n/a | # log10(10**n) = n |

3334 | n/a | if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1): |

3335 | n/a | # answer may need rounding |

3336 | n/a | ans = Decimal(self._exp + len(self._int) - 1) |

3337 | n/a | else: |

3338 | n/a | # result is irrational, so necessarily inexact |

3339 | n/a | op = _WorkRep(self) |

3340 | n/a | c, e = op.int, op.exp |

3341 | n/a | p = context.prec |

3342 | n/a | |

3343 | n/a | # correctly rounded result: repeatedly increase precision |

3344 | n/a | # until result is unambiguously roundable |

3345 | n/a | places = p-self._log10_exp_bound()+2 |

3346 | n/a | while True: |

3347 | n/a | coeff = _dlog10(c, e, places) |

3348 | n/a | # assert len(str(abs(coeff)))-p >= 1 |

3349 | n/a | if coeff % (5*10**(len(str(abs(coeff)))-p-1)): |

3350 | n/a | break |

3351 | n/a | places += 3 |

3352 | n/a | ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) |

3353 | n/a | |

3354 | n/a | context = context._shallow_copy() |

3355 | n/a | rounding = context._set_rounding(ROUND_HALF_EVEN) |

3356 | n/a | ans = ans._fix(context) |

3357 | n/a | context.rounding = rounding |

3358 | n/a | return ans |

3359 | n/a | |

3360 | n/a | def logb(self, context=None): |

3361 | n/a | """ Returns the exponent of the magnitude of self's MSD. |

3362 | n/a | |

3363 | n/a | The result is the integer which is the exponent of the magnitude |

3364 | n/a | of the most significant digit of self (as though it were truncated |

3365 | n/a | to a single digit while maintaining the value of that digit and |

3366 | n/a | without limiting the resulting exponent). |

3367 | n/a | """ |

3368 | n/a | # logb(NaN) = NaN |

3369 | n/a | ans = self._check_nans(context=context) |

3370 | n/a | if ans: |

3371 | n/a | return ans |

3372 | n/a | |

3373 | n/a | if context is None: |

3374 | n/a | context = getcontext() |

3375 | n/a | |

3376 | n/a | # logb(+/-Inf) = +Inf |

3377 | n/a | if self._isinfinity(): |

3378 | n/a | return _Infinity |

3379 | n/a | |

3380 | n/a | # logb(0) = -Inf, DivisionByZero |

3381 | n/a | if not self: |

3382 | n/a | return context._raise_error(DivisionByZero, 'logb(0)', 1) |

3383 | n/a | |

3384 | n/a | # otherwise, simply return the adjusted exponent of self, as a |

3385 | n/a | # Decimal. Note that no attempt is made to fit the result |

3386 | n/a | # into the current context. |

3387 | n/a | ans = Decimal(self.adjusted()) |

3388 | n/a | return ans._fix(context) |

3389 | n/a | |

3390 | n/a | def _islogical(self): |

3391 | n/a | """Return True if self is a logical operand. |

3392 | n/a | |

3393 | n/a | For being logical, it must be a finite number with a sign of 0, |

3394 | n/a | an exponent of 0, and a coefficient whose digits must all be |

3395 | n/a | either 0 or 1. |

3396 | n/a | """ |

3397 | n/a | if self._sign != 0 or self._exp != 0: |

3398 | n/a | return False |

3399 | n/a | for dig in self._int: |

3400 | n/a | if dig not in '01': |

3401 | n/a | return False |

3402 | n/a | return True |

3403 | n/a | |

3404 | n/a | def _fill_logical(self, context, opa, opb): |

3405 | n/a | dif = context.prec - len(opa) |

3406 | n/a | if dif > 0: |

3407 | n/a | opa = '0'*dif + opa |

3408 | n/a | elif dif < 0: |

3409 | n/a | opa = opa[-context.prec:] |

3410 | n/a | dif = context.prec - len(opb) |

3411 | n/a | if dif > 0: |

3412 | n/a | opb = '0'*dif + opb |

3413 | n/a | elif dif < 0: |

3414 | n/a | opb = opb[-context.prec:] |

3415 | n/a | return opa, opb |

3416 | n/a | |

3417 | n/a | def logical_and(self, other, context=None): |

3418 | n/a | """Applies an 'and' operation between self and other's digits.""" |

3419 | n/a | if context is None: |

3420 | n/a | context = getcontext() |

3421 | n/a | |

3422 | n/a | other = _convert_other(other, raiseit=True) |

3423 | n/a | |

3424 | n/a | if not self._islogical() or not other._islogical(): |

3425 | n/a | return context._raise_error(InvalidOperation) |

3426 | n/a | |

3427 | n/a | # fill to context.prec |

3428 | n/a | (opa, opb) = self._fill_logical(context, self._int, other._int) |

3429 | n/a | |

3430 | n/a | # make the operation, and clean starting zeroes |

3431 | n/a | result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)]) |

3432 | n/a | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |

3433 | n/a | |

3434 | n/a | def logical_invert(self, context=None): |

3435 | n/a | """Invert all its digits.""" |

3436 | n/a | if context is None: |

3437 | n/a | context = getcontext() |

3438 | n/a | return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0), |

3439 | n/a | context) |

3440 | n/a | |

3441 | n/a | def logical_or(self, other, context=None): |

3442 | n/a | """Applies an 'or' operation between self and other's digits.""" |

3443 | n/a | if context is None: |

3444 | n/a | context = getcontext() |

3445 | n/a | |

3446 | n/a | other = _convert_other(other, raiseit=True) |

3447 | n/a | |

3448 | n/a | if not self._islogical() or not other._islogical(): |

3449 | n/a | return context._raise_error(InvalidOperation) |

3450 | n/a | |

3451 | n/a | # fill to context.prec |

3452 | n/a | (opa, opb) = self._fill_logical(context, self._int, other._int) |

3453 | n/a | |

3454 | n/a | # make the operation, and clean starting zeroes |

3455 | n/a | result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)]) |

3456 | n/a | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |

3457 | n/a | |

3458 | n/a | def logical_xor(self, other, context=None): |

3459 | n/a | """Applies an 'xor' operation between self and other's digits.""" |

3460 | n/a | if context is None: |

3461 | n/a | context = getcontext() |

3462 | n/a | |

3463 | n/a | other = _convert_other(other, raiseit=True) |

3464 | n/a | |

3465 | n/a | if not self._islogical() or not other._islogical(): |

3466 | n/a | return context._raise_error(InvalidOperation) |

3467 | n/a | |

3468 | n/a | # fill to context.prec |

3469 | n/a | (opa, opb) = self._fill_logical(context, self._int, other._int) |

3470 | n/a | |

3471 | n/a | # make the operation, and clean starting zeroes |

3472 | n/a | result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)]) |

3473 | n/a | return _dec_from_triple(0, result.lstrip('0') or '0', 0) |

3474 | n/a | |

3475 | n/a | def max_mag(self, other, context=None): |

3476 | n/a | """Compares the values numerically with their sign ignored.""" |

3477 | n/a | other = _convert_other(other, raiseit=True) |

3478 | n/a | |

3479 | n/a | if context is None: |

3480 | n/a | context = getcontext() |

3481 | n/a | |

3482 | n/a | if self._is_special or other._is_special: |

3483 | n/a | # If one operand is a quiet NaN and the other is number, then the |

3484 | n/a | # number is always returned |

3485 | n/a | sn = self._isnan() |

3486 | n/a | on = other._isnan() |

3487 | n/a | if sn or on: |

3488 | n/a | if on == 1 and sn == 0: |

3489 | n/a | return self._fix(context) |

3490 | n/a | if sn == 1 and on == 0: |

3491 | n/a | return other._fix(context) |

3492 | n/a | return self._check_nans(other, context) |

3493 | n/a | |

3494 | n/a | c = self.copy_abs()._cmp(other.copy_abs()) |

3495 | n/a | if c == 0: |

3496 | n/a | c = self.compare_total(other) |

3497 | n/a | |

3498 | n/a | if c == -1: |

3499 | n/a | ans = other |

3500 | n/a | else: |

3501 | n/a | ans = self |

3502 | n/a | |

3503 | n/a | return ans._fix(context) |

3504 | n/a | |

3505 | n/a | def min_mag(self, other, context=None): |

3506 | n/a | """Compares the values numerically with their sign ignored.""" |

3507 | n/a | other = _convert_other(other, raiseit=True) |

3508 | n/a | |

3509 | n/a | if context is None: |

3510 | n/a | context = getcontext() |

3511 | n/a | |

3512 | n/a | if self._is_special or other._is_special: |

3513 | n/a | # If one operand is a quiet NaN and the other is number, then the |

3514 | n/a | # number is always returned |

3515 | n/a | sn = self._isnan() |

3516 | n/a | on = other._isnan() |

3517 | n/a | if sn or on: |

3518 | n/a | if on == 1 and sn == 0: |

3519 | n/a | return self._fix(context) |

3520 | n/a | if sn == 1 and on == 0: |

3521 | n/a | return other._fix(context) |

3522 | n/a | return self._check_nans(other, context) |

3523 | n/a | |

3524 | n/a | c = self.copy_abs()._cmp(other.copy_abs()) |

3525 | n/a | if c == 0: |

3526 | n/a | c = self.compare_total(other) |

3527 | n/a | |

3528 | n/a | if c == -1: |

3529 | n/a | ans = self |

3530 | n/a | else: |

3531 | n/a | ans = other |

3532 | n/a | |

3533 | n/a | return ans._fix(context) |

3534 | n/a | |

3535 | n/a | def next_minus(self, context=None): |

3536 | n/a | """Returns the largest representable number smaller than itself.""" |

3537 | n/a | if context is None: |

3538 | n/a | context = getcontext() |

3539 | n/a | |

3540 | n/a | ans = self._check_nans(context=context) |

3541 | n/a | if ans: |

3542 | n/a | return ans |

3543 | n/a | |

3544 | n/a | if self._isinfinity() == -1: |

3545 | n/a | return _NegativeInfinity |

3546 | n/a | if self._isinfinity() == 1: |

3547 | n/a | return _dec_from_triple(0, '9'*context.prec, context.Etop()) |

3548 | n/a | |

3549 | n/a | context = context.copy() |

3550 | n/a | context._set_rounding(ROUND_FLOOR) |

3551 | n/a | context._ignore_all_flags() |

3552 | n/a | new_self = self._fix(context) |

3553 | n/a | if new_self != self: |

3554 | n/a | return new_self |

3555 | n/a | return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1), |

3556 | n/a | context) |

3557 | n/a | |

3558 | n/a | def next_plus(self, context=None): |

3559 | n/a | """Returns the smallest representable number larger than itself.""" |

3560 | n/a | if context is None: |

3561 | n/a | context = getcontext() |

3562 | n/a | |

3563 | n/a | ans = self._check_nans(context=context) |

3564 | n/a | if ans: |

3565 | n/a | return ans |

3566 | n/a | |

3567 | n/a | if self._isinfinity() == 1: |

3568 | n/a | return _Infinity |

3569 | n/a | if self._isinfinity() == -1: |

3570 | n/a | return _dec_from_triple(1, '9'*context.prec, context.Etop()) |

3571 | n/a | |

3572 | n/a | context = context.copy() |

3573 | n/a | context._set_rounding(ROUND_CEILING) |

3574 | n/a | context._ignore_all_flags() |

3575 | n/a | new_self = self._fix(context) |

3576 | n/a | if new_self != self: |

3577 | n/a | return new_self |

3578 | n/a | return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1), |

3579 | n/a | context) |

3580 | n/a | |

3581 | n/a | def next_toward(self, other, context=None): |

3582 | n/a | """Returns the number closest to self, in the direction towards other. |

3583 | n/a | |

3584 | n/a | The result is the closest representable number to self |

3585 | n/a | (excluding self) that is in the direction towards other, |

3586 | n/a | unless both have the same value. If the two operands are |

3587 | n/a | numerically equal, then the result is a copy of self with the |

3588 | n/a | sign set to be the same as the sign of other. |

3589 | n/a | """ |

3590 | n/a | other = _convert_other(other, raiseit=True) |

3591 | n/a | |

3592 | n/a | if context is None: |

3593 | n/a | context = getcontext() |

3594 | n/a | |

3595 | n/a | ans = self._check_nans(other, context) |

3596 | n/a | if ans: |

3597 | n/a | return ans |

3598 | n/a | |

3599 | n/a | comparison = self._cmp(other) |

3600 | n/a | if comparison == 0: |

3601 | n/a | return self.copy_sign(other) |

3602 | n/a | |

3603 | n/a | if comparison == -1: |

3604 | n/a | ans = self.next_plus(context) |

3605 | n/a | else: # comparison == 1 |

3606 | n/a | ans = self.next_minus(context) |

3607 | n/a | |

3608 | n/a | # decide which flags to raise using value of ans |

3609 | n/a | if ans._isinfinity(): |

3610 | n/a | context._raise_error(Overflow, |

3611 | n/a | 'Infinite result from next_toward', |

3612 | n/a | ans._sign) |

3613 | n/a | context._raise_error(Inexact) |

3614 | n/a | context._raise_error(Rounded) |

3615 | n/a | elif ans.adjusted() < context.Emin: |

3616 | n/a | context._raise_error(Underflow) |

3617 | n/a | context._raise_error(Subnormal) |

3618 | n/a | context._raise_error(Inexact) |

3619 | n/a | context._raise_error(Rounded) |

3620 | n/a | # if precision == 1 then we don't raise Clamped for a |

3621 | n/a | # result 0E-Etiny. |

3622 | n/a | if not ans: |

3623 | n/a | context._raise_error(Clamped) |

3624 | n/a | |

3625 | n/a | return ans |

3626 | n/a | |

3627 | n/a | def number_class(self, context=None): |

3628 | n/a | """Returns an indication of the class of self. |

3629 | n/a | |

3630 | n/a | The class is one of the following strings: |

3631 | n/a | sNaN |

3632 | n/a | NaN |

3633 | n/a | -Infinity |

3634 | n/a | -Normal |

3635 | n/a | -Subnormal |

3636 | n/a | -Zero |

3637 | n/a | +Zero |

3638 | n/a | +Subnormal |

3639 | n/a | +Normal |

3640 | n/a | +Infinity |

3641 | n/a | """ |

3642 | n/a | if self.is_snan(): |

3643 | n/a | return "sNaN" |

3644 | n/a | if self.is_qnan(): |

3645 | n/a | return "NaN" |

3646 | n/a | inf = self._isinfinity() |

3647 | n/a | if inf == 1: |

3648 | n/a | return "+Infinity" |

3649 | n/a | if inf == -1: |

3650 | n/a | return "-Infinity" |

3651 | n/a | if self.is_zero(): |

3652 | n/a | if self._sign: |

3653 | n/a | return "-Zero" |

3654 | n/a | else: |

3655 | n/a | return "+Zero" |

3656 | n/a | if context is None: |

3657 | n/a | context = getcontext() |

3658 | n/a | if self.is_subnormal(context=context): |

3659 | n/a | if self._sign: |

3660 | n/a | return "-Subnormal" |

3661 | n/a | else: |

3662 | n/a | return "+Subnormal" |

3663 | n/a | # just a normal, regular, boring number, :) |

3664 | n/a | if self._sign: |

3665 | n/a | return "-Normal" |

3666 | n/a | else: |

3667 | n/a | return "+Normal" |

3668 | n/a | |

3669 | n/a | def radix(self): |

3670 | n/a | """Just returns 10, as this is Decimal, :)""" |

3671 | n/a | return Decimal(10) |

3672 | n/a | |

3673 | n/a | def rotate(self, other, context=None): |

3674 | n/a | """Returns a rotated copy of self, value-of-other times.""" |

3675 | n/a | if context is None: |

3676 | n/a | context = getcontext() |

3677 | n/a | |

3678 | n/a | other = _convert_other(other, raiseit=True) |

3679 | n/a | |

3680 | n/a | ans = self._check_nans(other, context) |

3681 | n/a | if ans: |

3682 | n/a | return ans |

3683 | n/a | |

3684 | n/a | if other._exp != 0: |

3685 | n/a | return context._raise_error(InvalidOperation) |

3686 | n/a | if not (-context.prec <= int(other) <= context.prec): |

3687 | n/a | return context._raise_error(InvalidOperation) |

3688 | n/a | |

3689 | n/a | if self._isinfinity(): |

3690 | n/a | return Decimal(self) |

3691 | n/a | |

3692 | n/a | # get values, pad if necessary |

3693 | n/a | torot = int(other) |

3694 | n/a | rotdig = self._int |

3695 | n/a | topad = context.prec - len(rotdig) |

3696 | n/a | if topad > 0: |

3697 | n/a | rotdig = '0'*topad + rotdig |

3698 | n/a | elif topad < 0: |

3699 | n/a | rotdig = rotdig[-topad:] |

3700 | n/a | |

3701 | n/a | # let's rotate! |

3702 | n/a | rotated = rotdig[torot:] + rotdig[:torot] |

3703 | n/a | return _dec_from_triple(self._sign, |

3704 | n/a | rotated.lstrip('0') or '0', self._exp) |

3705 | n/a | |

3706 | n/a | def scaleb(self, other, context=None): |

3707 | n/a | """Returns self operand after adding the second value to its exp.""" |

3708 | n/a | if context is None: |

3709 | n/a | context = getcontext() |

3710 | n/a | |

3711 | n/a | other = _convert_other(other, raiseit=True) |

3712 | n/a | |

3713 | n/a | ans = self._check_nans(other, context) |

3714 | n/a | if ans: |

3715 | n/a | return ans |

3716 | n/a | |

3717 | n/a | if other._exp != 0: |

3718 | n/a | return context._raise_error(InvalidOperation) |

3719 | n/a | liminf = -2 * (context.Emax + context.prec) |

3720 | n/a | limsup = 2 * (context.Emax + context.prec) |

3721 | n/a | if not (liminf <= int(other) <= limsup): |

3722 | n/a | return context._raise_error(InvalidOperation) |

3723 | n/a | |

3724 | n/a | if self._isinfinity(): |

3725 | n/a | return Decimal(self) |

3726 | n/a | |

3727 | n/a | d = _dec_from_triple(self._sign, self._int, self._exp + int(other)) |

3728 | n/a | d = d._fix(context) |

3729 | n/a | return d |

3730 | n/a | |

3731 | n/a | def shift(self, other, context=None): |

3732 | n/a | """Returns a shifted copy of self, value-of-other times.""" |

3733 | n/a | if context is None: |

3734 | n/a | context = getcontext() |

3735 | n/a | |

3736 | n/a | other = _convert_other(other, raiseit=True) |

3737 | n/a | |

3738 | n/a | ans = self._check_nans(other, context) |

3739 | n/a | if ans: |

3740 | n/a | return ans |

3741 | n/a | |

3742 | n/a | if other._exp != 0: |

3743 | n/a | return context._raise_error(InvalidOperation) |

3744 | n/a | if not (-context.prec <= int(other) <= context.prec): |

3745 | n/a | return context._raise_error(InvalidOperation) |

3746 | n/a | |

3747 | n/a | if self._isinfinity(): |

3748 | n/a | return Decimal(self) |

3749 | n/a | |

3750 | n/a | # get values, pad if necessary |

3751 | n/a | torot = int(other) |

3752 | n/a | rotdig = self._int |

3753 | n/a | topad = context.prec - len(rotdig) |

3754 | n/a | if topad > 0: |

3755 | n/a | rotdig = '0'*topad + rotdig |

3756 | n/a | elif topad < 0: |

3757 | n/a | rotdig = rotdig[-topad:] |

3758 | n/a | |

3759 | n/a | # let's shift! |

3760 | n/a | if torot < 0: |

3761 | n/a | shifted = rotdig[:torot] |

3762 | n/a | else: |

3763 | n/a | shifted = rotdig + '0'*torot |

3764 | n/a | shifted = shifted[-context.prec:] |

3765 | n/a | |

3766 | n/a | return _dec_from_triple(self._sign, |

3767 | n/a | shifted.lstrip('0') or '0', self._exp) |

3768 | n/a | |

3769 | n/a | # Support for pickling, copy, and deepcopy |

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

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

3772 | n/a | |

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

3774 | n/a | if type(self) is Decimal: |

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

3776 | n/a | return self.__class__(str(self)) |

3777 | n/a | |

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

3779 | n/a | if type(self) is Decimal: |

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

3781 | n/a | return self.__class__(str(self)) |

3782 | n/a | |

3783 | n/a | # PEP 3101 support. the _localeconv keyword argument should be |

3784 | n/a | # considered private: it's provided for ease of testing only. |

3785 | n/a | def __format__(self, specifier, context=None, _localeconv=None): |

3786 | n/a | """Format a Decimal instance according to the given specifier. |

3787 | n/a | |

3788 | n/a | The specifier should be a standard format specifier, with the |

3789 | n/a | form described in PEP 3101. Formatting types 'e', 'E', 'f', |

3790 | n/a | 'F', 'g', 'G', 'n' and '%' are supported. If the formatting |

3791 | n/a | type is omitted it defaults to 'g' or 'G', depending on the |

3792 | n/a | value of context.capitals. |

3793 | n/a | """ |

3794 | n/a | |

3795 | n/a | # Note: PEP 3101 says that if the type is not present then |

3796 | n/a | # there should be at least one digit after the decimal point. |

3797 | n/a | # We take the liberty of ignoring this requirement for |

3798 | n/a | # Decimal---it's presumably there to make sure that |

3799 | n/a | # format(float, '') behaves similarly to str(float). |

3800 | n/a | if context is None: |

3801 | n/a | context = getcontext() |

3802 | n/a | |

3803 | n/a | spec = _parse_format_specifier(specifier, _localeconv=_localeconv) |

3804 | n/a | |

3805 | n/a | # special values don't care about the type or precision |

3806 | n/a | if self._is_special: |

3807 | n/a | sign = _format_sign(self._sign, spec) |

3808 | n/a | body = str(self.copy_abs()) |

3809 | n/a | if spec['type'] == '%': |

3810 | n/a | body += '%' |

3811 | n/a | return _format_align(sign, body, spec) |

3812 | n/a | |

3813 | n/a | # a type of None defaults to 'g' or 'G', depending on context |

3814 | n/a | if spec['type'] is None: |

3815 | n/a | spec['type'] = ['g', 'G'][context.capitals] |

3816 | n/a | |

3817 | n/a | # if type is '%', adjust exponent of self accordingly |

3818 | n/a | if spec['type'] == '%': |

3819 | n/a | self = _dec_from_triple(self._sign, self._int, self._exp+2) |

3820 | n/a | |

3821 | n/a | # round if necessary, taking rounding mode from the context |

3822 | n/a | rounding = context.rounding |

3823 | n/a | precision = spec['precision'] |

3824 | n/a | if precision is not None: |

3825 | n/a | if spec['type'] in 'eE': |

3826 | n/a | self = self._round(precision+1, rounding) |

3827 | n/a | elif spec['type'] in 'fF%': |

3828 | n/a | self = self._rescale(-precision, rounding) |

3829 | n/a | elif spec['type'] in 'gG' and len(self._int) > precision: |

3830 | n/a | self = self._round(precision, rounding) |

3831 | n/a | # special case: zeros with a positive exponent can't be |

3832 | n/a | # represented in fixed point; rescale them to 0e0. |

3833 | n/a | if not self and self._exp > 0 and spec['type'] in 'fF%': |

3834 | n/a | self = self._rescale(0, rounding) |

3835 | n/a | |

3836 | n/a | # figure out placement of the decimal point |

3837 | n/a | leftdigits = self._exp + len(self._int) |

3838 | n/a | if spec['type'] in 'eE': |

3839 | n/a | if not self and precision is not None: |

3840 | n/a | dotplace = 1 - precision |

3841 | n/a | else: |

3842 | n/a | dotplace = 1 |

3843 | n/a | elif spec['type'] in 'fF%': |

3844 | n/a | dotplace = leftdigits |

3845 | n/a | elif spec['type'] in 'gG': |

3846 | n/a | if self._exp <= 0 and leftdigits > -6: |

3847 | n/a | dotplace = leftdigits |

3848 | n/a | else: |

3849 | n/a | dotplace = 1 |

3850 | n/a | |

3851 | n/a | # find digits before and after decimal point, and get exponent |

3852 | n/a | if dotplace < 0: |

3853 | n/a | intpart = '0' |

3854 | n/a | fracpart = '0'*(-dotplace) + self._int |

3855 | n/a | elif dotplace > len(self._int): |

3856 | n/a | intpart = self._int + '0'*(dotplace-len(self._int)) |

3857 | n/a | fracpart = '' |

3858 | n/a | else: |

3859 | n/a | intpart = self._int[:dotplace] or '0' |

3860 | n/a | fracpart = self._int[dotplace:] |

3861 | n/a | exp = leftdigits-dotplace |

3862 | n/a | |

3863 | n/a | # done with the decimal-specific stuff; hand over the rest |

3864 | n/a | # of the formatting to the _format_number function |

3865 | n/a | return _format_number(self._sign, intpart, fracpart, exp, spec) |

3866 | n/a | |

3867 | n/a | def _dec_from_triple(sign, coefficient, exponent, special=False): |

3868 | n/a | """Create a decimal instance directly, without any validation, |

3869 | n/a | normalization (e.g. removal of leading zeros) or argument |

3870 | n/a | conversion. |

3871 | n/a | |

3872 | n/a | This function is for *internal use only*. |

3873 | n/a | """ |

3874 | n/a | |

3875 | n/a | self = object.__new__(Decimal) |

3876 | n/a | self._sign = sign |

3877 | n/a | self._int = coefficient |

3878 | n/a | self._exp = exponent |

3879 | n/a | self._is_special = special |

3880 | n/a | |

3881 | n/a | return self |

3882 | n/a | |

3883 | n/a | # Register Decimal as a kind of Number (an abstract base class). |

3884 | n/a | # However, do not register it as Real (because Decimals are not |

3885 | n/a | # interoperable with floats). |

3886 | n/a | _numbers.Number.register(Decimal) |

3887 | n/a | |

3888 | n/a | |

3889 | n/a | ##### Context class ####################################################### |

3890 | n/a | |

3891 | n/a | class _ContextManager(object): |

3892 | n/a | """Context manager class to support localcontext(). |

3893 | n/a | |

3894 | n/a | Sets a copy of the supplied context in __enter__() and restores |

3895 | n/a | the previous decimal context in __exit__() |

3896 | n/a | """ |

3897 | n/a | def __init__(self, new_context): |

3898 | n/a | self.new_context = new_context.copy() |

3899 | n/a | def __enter__(self): |

3900 | n/a | self.saved_context = getcontext() |

3901 | n/a | setcontext(self.new_context) |

3902 | n/a | return self.new_context |

3903 | n/a | def __exit__(self, t, v, tb): |

3904 | n/a | setcontext(self.saved_context) |

3905 | n/a | |

3906 | n/a | class Context(object): |

3907 | n/a | """Contains the context for a Decimal instance. |

3908 | n/a | |

3909 | n/a | Contains: |

3910 | n/a | prec - precision (for use in rounding, division, square roots..) |

3911 | n/a | rounding - rounding type (how you round) |

3912 | n/a | traps - If traps[exception] = 1, then the exception is |

3913 | n/a | raised when it is caused. Otherwise, a value is |

3914 | n/a | substituted in. |

3915 | n/a | flags - When an exception is caused, flags[exception] is set. |

3916 | n/a | (Whether or not the trap_enabler is set) |

3917 | n/a | Should be reset by user of Decimal instance. |

3918 | n/a | Emin - Minimum exponent |

3919 | n/a | Emax - Maximum exponent |

3920 | n/a | capitals - If 1, 1*10^1 is printed as 1E+1. |

3921 | n/a | If 0, printed as 1e1 |

3922 | n/a | clamp - If 1, change exponents if too high (Default 0) |

3923 | n/a | """ |

3924 | n/a | |

3925 | n/a | def __init__(self, prec=None, rounding=None, Emin=None, Emax=None, |

3926 | n/a | capitals=None, clamp=None, flags=None, traps=None, |

3927 | n/a | _ignored_flags=None): |

3928 | n/a | # Set defaults; for everything except flags and _ignored_flags, |

3929 | n/a | # inherit from DefaultContext. |

3930 | n/a | try: |

3931 | n/a | dc = DefaultContext |

3932 | n/a | except NameError: |

3933 | n/a | pass |

3934 | n/a | |

3935 | n/a | self.prec = prec if prec is not None else dc.prec |

3936 | n/a | self.rounding = rounding if rounding is not None else dc.rounding |

3937 | n/a | self.Emin = Emin if Emin is not None else dc.Emin |

3938 | n/a | self.Emax = Emax if Emax is not None else dc.Emax |

3939 | n/a | self.capitals = capitals if capitals is not None else dc.capitals |

3940 | n/a | self.clamp = clamp if clamp is not None else dc.clamp |

3941 | n/a | |

3942 | n/a | if _ignored_flags is None: |

3943 | n/a | self._ignored_flags = [] |

3944 | n/a | else: |

3945 | n/a | self._ignored_flags = _ignored_flags |

3946 | n/a | |

3947 | n/a | if traps is None: |

3948 | n/a | self.traps = dc.traps.copy() |

3949 | n/a | elif not isinstance(traps, dict): |

3950 | n/a | self.traps = dict((s, int(s in traps)) for s in _signals + traps) |

3951 | n/a | else: |

3952 | n/a | self.traps = traps |

3953 | n/a | |

3954 | n/a | if flags is None: |

3955 | n/a | self.flags = dict.fromkeys(_signals, 0) |

3956 | n/a | elif not isinstance(flags, dict): |

3957 | n/a | self.flags = dict((s, int(s in flags)) for s in _signals + flags) |

3958 | n/a | else: |

3959 | n/a | self.flags = flags |

3960 | n/a | |

3961 | n/a | def _set_integer_check(self, name, value, vmin, vmax): |

3962 | n/a | if not isinstance(value, int): |

3963 | n/a | raise TypeError("%s must be an integer" % name) |

3964 | n/a | if vmin == '-inf': |

3965 | n/a | if value > vmax: |

3966 | n/a | raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value)) |

3967 | n/a | elif vmax == 'inf': |

3968 | n/a | if value < vmin: |

3969 | n/a | raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value)) |

3970 | n/a | else: |

3971 | n/a | if value < vmin or value > vmax: |

3972 | n/a | raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value)) |

3973 | n/a | return object.__setattr__(self, name, value) |

3974 | n/a | |

3975 | n/a | def _set_signal_dict(self, name, d): |

3976 | n/a | if not isinstance(d, dict): |

3977 | n/a | raise TypeError("%s must be a signal dict" % d) |

3978 | n/a | for key in d: |

3979 | n/a | if not key in _signals: |

3980 | n/a | raise KeyError("%s is not a valid signal dict" % d) |

3981 | n/a | for key in _signals: |

3982 | n/a | if not key in d: |

3983 | n/a | raise KeyError("%s is not a valid signal dict" % d) |

3984 | n/a | return object.__setattr__(self, name, d) |

3985 | n/a | |

3986 | n/a | def __setattr__(self, name, value): |

3987 | n/a | if name == 'prec': |

3988 | n/a | return self._set_integer_check(name, value, 1, 'inf') |

3989 | n/a | elif name == 'Emin': |

3990 | n/a | return self._set_integer_check(name, value, '-inf', 0) |

3991 | n/a | elif name == 'Emax': |

3992 | n/a | return self._set_integer_check(name, value, 0, 'inf') |

3993 | n/a | elif name == 'capitals': |

3994 | n/a | return self._set_integer_check(name, value, 0, 1) |

3995 | n/a | elif name == 'clamp': |

3996 | n/a | return self._set_integer_check(name, value, 0, 1) |

3997 | n/a | elif name == 'rounding': |

3998 | n/a | if not value in _rounding_modes: |

3999 | n/a | # raise TypeError even for strings to have consistency |

4000 | n/a | # among various implementations. |

4001 | n/a | raise TypeError("%s: invalid rounding mode" % value) |

4002 | n/a | return object.__setattr__(self, name, value) |

4003 | n/a | elif name == 'flags' or name == 'traps': |

4004 | n/a | return self._set_signal_dict(name, value) |

4005 | n/a | elif name == '_ignored_flags': |

4006 | n/a | return object.__setattr__(self, name, value) |

4007 | n/a | else: |

4008 | n/a | raise AttributeError( |

4009 | n/a | "'decimal.Context' object has no attribute '%s'" % name) |

4010 | n/a | |

4011 | n/a | def __delattr__(self, name): |

4012 | n/a | raise AttributeError("%s cannot be deleted" % name) |

4013 | n/a | |

4014 | n/a | # Support for pickling, copy, and deepcopy |

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

4016 | n/a | flags = [sig for sig, v in self.flags.items() if v] |

4017 | n/a | traps = [sig for sig, v in self.traps.items() if v] |

4018 | n/a | return (self.__class__, |

4019 | n/a | (self.prec, self.rounding, self.Emin, self.Emax, |

4020 | n/a | self.capitals, self.clamp, flags, traps)) |

4021 | n/a | |

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

4023 | n/a | """Show the current context.""" |

4024 | n/a | s = [] |

4025 | n/a | s.append('Context(prec=%(prec)d, rounding=%(rounding)s, ' |

4026 | n/a | 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, ' |

4027 | n/a | 'clamp=%(clamp)d' |

4028 | n/a | % vars(self)) |

4029 | n/a | names = [f.__name__ for f, v in self.flags.items() if v] |

4030 | n/a | s.append('flags=[' + ', '.join(names) + ']') |

4031 | n/a | names = [t.__name__ for t, v in self.traps.items() if v] |

4032 | n/a | s.append('traps=[' + ', '.join(names) + ']') |

4033 | n/a | return ', '.join(s) + ')' |

4034 | n/a | |

4035 | n/a | def clear_flags(self): |

4036 | n/a | """Reset all flags to zero""" |

4037 | n/a | for flag in self.flags: |

4038 | n/a | self.flags[flag] = 0 |

4039 | n/a | |

4040 | n/a | def clear_traps(self): |

4041 | n/a | """Reset all traps to zero""" |

4042 | n/a | for flag in self.traps: |

4043 | n/a | self.traps[flag] = 0 |

4044 | n/a | |

4045 | n/a | def _shallow_copy(self): |

4046 | n/a | """Returns a shallow copy from self.""" |

4047 | n/a | nc = Context(self.prec, self.rounding, self.Emin, self.Emax, |

4048 | n/a | self.capitals, self.clamp, self.flags, self.traps, |

4049 | n/a | self._ignored_flags) |

4050 | n/a | return nc |

4051 | n/a | |

4052 | n/a | def copy(self): |

4053 | n/a | """Returns a deep copy from self.""" |

4054 | n/a | nc = Context(self.prec, self.rounding, self.Emin, self.Emax, |

4055 | n/a | self.capitals, self.clamp, |

4056 | n/a | self.flags.copy(), self.traps.copy(), |

4057 | n/a | self._ignored_flags) |

4058 | n/a | return nc |

4059 | n/a | __copy__ = copy |

4060 | n/a | |

4061 | n/a | def _raise_error(self, condition, explanation = None, *args): |

4062 | n/a | """Handles an error |

4063 | n/a | |

4064 | n/a | If the flag is in _ignored_flags, returns the default response. |

4065 | n/a | Otherwise, it sets the flag, then, if the corresponding |

4066 | n/a | trap_enabler is set, it reraises the exception. Otherwise, it returns |

4067 | n/a | the default value after setting the flag. |

4068 | n/a | """ |

4069 | n/a | error = _condition_map.get(condition, condition) |

4070 | n/a | if error in self._ignored_flags: |

4071 | n/a | # Don't touch the flag |

4072 | n/a | return error().handle(self, *args) |

4073 | n/a | |

4074 | n/a | self.flags[error] = 1 |

4075 | n/a | if not self.traps[error]: |

4076 | n/a | # The errors define how to handle themselves. |

4077 | n/a | return condition().handle(self, *args) |

4078 | n/a | |

4079 | n/a | # Errors should only be risked on copies of the context |

4080 | n/a | # self._ignored_flags = [] |

4081 | n/a | raise error(explanation) |

4082 | n/a | |

4083 | n/a | def _ignore_all_flags(self): |

4084 | n/a | """Ignore all flags, if they are raised""" |

4085 | n/a | return self._ignore_flags(*_signals) |

4086 | n/a | |

4087 | n/a | def _ignore_flags(self, *flags): |

4088 | n/a | """Ignore the flags, if they are raised""" |

4089 | n/a | # Do not mutate-- This way, copies of a context leave the original |

4090 | n/a | # alone. |

4091 | n/a | self._ignored_flags = (self._ignored_flags + list(flags)) |

4092 | n/a | return list(flags) |

4093 | n/a | |

4094 | n/a | def _regard_flags(self, *flags): |

4095 | n/a | """Stop ignoring the flags, if they are raised""" |

4096 | n/a | if flags and isinstance(flags[0], (tuple,list)): |

4097 | n/a | flags = flags[0] |

4098 | n/a | for flag in flags: |

4099 | n/a | self._ignored_flags.remove(flag) |

4100 | n/a | |

4101 | n/a | # We inherit object.__hash__, so we must deny this explicitly |

4102 | n/a | __hash__ = None |

4103 | n/a | |

4104 | n/a | def Etiny(self): |

4105 | n/a | """Returns Etiny (= Emin - prec + 1)""" |

4106 | n/a | return int(self.Emin - self.prec + 1) |

4107 | n/a | |

4108 | n/a | def Etop(self): |

4109 | n/a | """Returns maximum exponent (= Emax - prec + 1)""" |

4110 | n/a | return int(self.Emax - self.prec + 1) |

4111 | n/a | |

4112 | n/a | def _set_rounding(self, type): |

4113 | n/a | """Sets the rounding type. |

4114 | n/a | |

4115 | n/a | Sets the rounding type, and returns the current (previous) |

4116 | n/a | rounding type. Often used like: |

4117 | n/a | |

4118 | n/a | context = context.copy() |

4119 | n/a | # so you don't change the calling context |

4120 | n/a | # if an error occurs in the middle. |

4121 | n/a | rounding = context._set_rounding(ROUND_UP) |

4122 | n/a | val = self.__sub__(other, context=context) |

4123 | n/a | context._set_rounding(rounding) |

4124 | n/a | |

4125 | n/a | This will make it round up for that operation. |

4126 | n/a | """ |

4127 | n/a | rounding = self.rounding |

4128 | n/a | self.rounding = type |

4129 | n/a | return rounding |

4130 | n/a | |

4131 | n/a | def create_decimal(self, num='0'): |

4132 | n/a | """Creates a new Decimal instance but using self as context. |

4133 | n/a | |

4134 | n/a | This method implements the to-number operation of the |

4135 | n/a | IBM Decimal specification.""" |

4136 | n/a | |

4137 | n/a | if isinstance(num, str) and (num != num.strip() or '_' in num): |

4138 | n/a | return self._raise_error(ConversionSyntax, |

4139 | n/a | "trailing or leading whitespace and " |

4140 | n/a | "underscores are not permitted.") |

4141 | n/a | |

4142 | n/a | d = Decimal(num, context=self) |

4143 | n/a | if d._isnan() and len(d._int) > self.prec - self.clamp: |

4144 | n/a | return self._raise_error(ConversionSyntax, |

4145 | n/a | "diagnostic info too long in NaN") |

4146 | n/a | return d._fix(self) |

4147 | n/a | |

4148 | n/a | def create_decimal_from_float(self, f): |

4149 | n/a | """Creates a new Decimal instance from a float but rounding using self |

4150 | n/a | as the context. |

4151 | n/a | |

4152 | n/a | >>> context = Context(prec=5, rounding=ROUND_DOWN) |

4153 | n/a | >>> context.create_decimal_from_float(3.1415926535897932) |

4154 | n/a | Decimal('3.1415') |

4155 | n/a | >>> context = Context(prec=5, traps=[Inexact]) |

4156 | n/a | >>> context.create_decimal_from_float(3.1415926535897932) |

4157 | n/a | Traceback (most recent call last): |

4158 | n/a | ... |

4159 | n/a | decimal.Inexact: None |

4160 | n/a | |

4161 | n/a | """ |

4162 | n/a | d = Decimal.from_float(f) # An exact conversion |

4163 | n/a | return d._fix(self) # Apply the context rounding |

4164 | n/a | |

4165 | n/a | # Methods |

4166 | n/a | def abs(self, a): |

4167 | n/a | """Returns the absolute value of the operand. |

4168 | n/a | |

4169 | n/a | If the operand is negative, the result is the same as using the minus |

4170 | n/a | operation on the operand. Otherwise, the result is the same as using |

4171 | n/a | the plus operation on the operand. |

4172 | n/a | |

4173 | n/a | >>> ExtendedContext.abs(Decimal('2.1')) |

4174 | n/a | Decimal('2.1') |

4175 | n/a | >>> ExtendedContext.abs(Decimal('-100')) |

4176 | n/a | Decimal('100') |

4177 | n/a | >>> ExtendedContext.abs(Decimal('101.5')) |

4178 | n/a | Decimal('101.5') |

4179 | n/a | >>> ExtendedContext.abs(Decimal('-101.5')) |

4180 | n/a | Decimal('101.5') |

4181 | n/a | >>> ExtendedContext.abs(-1) |

4182 | n/a | Decimal('1') |

4183 | n/a | """ |

4184 | n/a | a = _convert_other(a, raiseit=True) |

4185 | n/a | return a.__abs__(context=self) |

4186 | n/a | |

4187 | n/a | def add(self, a, b): |

4188 | n/a | """Return the sum of the two operands. |

4189 | n/a | |

4190 | n/a | >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) |

4191 | n/a | Decimal('19.00') |

4192 | n/a | >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) |

4193 | n/a | Decimal('1.02E+4') |

4194 | n/a | >>> ExtendedContext.add(1, Decimal(2)) |

4195 | n/a | Decimal('3') |

4196 | n/a | >>> ExtendedContext.add(Decimal(8), 5) |

4197 | n/a | Decimal('13') |

4198 | n/a | >>> ExtendedContext.add(5, 5) |

4199 | n/a | Decimal('10') |

4200 | n/a | """ |

4201 | n/a | a = _convert_other(a, raiseit=True) |

4202 | n/a | r = a.__add__(b, context=self) |

4203 | n/a | if r is NotImplemented: |

4204 | n/a | raise TypeError("Unable to convert %s to Decimal" % b) |

4205 | n/a | else: |

4206 | n/a | return r |

4207 | n/a | |

4208 | n/a | def _apply(self, a): |

4209 | n/a | return str(a._fix(self)) |

4210 | n/a | |

4211 | n/a | def canonical(self, a): |

4212 | n/a | """Returns the same Decimal object. |

4213 | n/a | |

4214 | n/a | As we do not have different encodings for the same number, the |

4215 | n/a | received object already is in its canonical form. |

4216 | n/a | |

4217 | n/a | >>> ExtendedContext.canonical(Decimal('2.50')) |

4218 | n/a | Decimal('2.50') |

4219 | n/a | """ |

4220 | n/a | if not isinstance(a, Decimal): |

4221 | n/a | raise TypeError("canonical requires a Decimal as an argument.") |

4222 | n/a | return a.canonical() |

4223 | n/a | |

4224 | n/a | def compare(self, a, b): |

4225 | n/a | """Compares values numerically. |

4226 | n/a | |

4227 | n/a | If the signs of the operands differ, a value representing each operand |

4228 | n/a | ('-1' if the operand is less than zero, '0' if the operand is zero or |

4229 | n/a | negative zero, or '1' if the operand is greater than zero) is used in |

4230 | n/a | place of that operand for the comparison instead of the actual |

4231 | n/a | operand. |

4232 | n/a | |

4233 | n/a | The comparison is then effected by subtracting the second operand from |

4234 | n/a | the first and then returning a value according to the result of the |

4235 | n/a | subtraction: '-1' if the result is less than zero, '0' if the result is |

4236 | n/a | zero or negative zero, or '1' if the result is greater than zero. |

4237 | n/a | |

4238 | n/a | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) |

4239 | n/a | Decimal('-1') |

4240 | n/a | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) |

4241 | n/a | Decimal('0') |

4242 | n/a | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) |

4243 | n/a | Decimal('0') |

4244 | n/a | >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) |

4245 | n/a | Decimal('1') |

4246 | n/a | >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) |

4247 | n/a | Decimal('1') |

4248 | n/a | >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) |

4249 | n/a | Decimal('-1') |

4250 | n/a | >>> ExtendedContext.compare(1, 2) |

4251 | n/a | Decimal('-1') |

4252 | n/a | >>> ExtendedContext.compare(Decimal(1), 2) |

4253 | n/a | Decimal('-1') |

4254 | n/a | >>> ExtendedContext.compare(1, Decimal(2)) |

4255 | n/a | Decimal('-1') |

4256 | n/a | """ |

4257 | n/a | a = _convert_other(a, raiseit=True) |

4258 | n/a | return a.compare(b, context=self) |

4259 | n/a | |

4260 | n/a | def compare_signal(self, a, b): |

4261 | n/a | """Compares the values of the two operands numerically. |

4262 | n/a | |

4263 | n/a | It's pretty much like compare(), but all NaNs signal, with signaling |

4264 | n/a | NaNs taking precedence over quiet NaNs. |

4265 | n/a | |

4266 | n/a | >>> c = ExtendedContext |

4267 | n/a | >>> c.compare_signal(Decimal('2.1'), Decimal('3')) |

4268 | n/a | Decimal('-1') |

4269 | n/a | >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) |

4270 | n/a | Decimal('0') |

4271 | n/a | >>> c.flags[InvalidOperation] = 0 |

4272 | n/a | >>> print(c.flags[InvalidOperation]) |

4273 | n/a | 0 |

4274 | n/a | >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) |

4275 | n/a | Decimal('NaN') |

4276 | n/a | >>> print(c.flags[InvalidOperation]) |

4277 | n/a | 1 |

4278 | n/a | >>> c.flags[InvalidOperation] = 0 |

4279 | n/a | >>> print(c.flags[InvalidOperation]) |

4280 | n/a | 0 |

4281 | n/a | >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) |

4282 | n/a | Decimal('NaN') |

4283 | n/a | >>> print(c.flags[InvalidOperation]) |

4284 | n/a | 1 |

4285 | n/a | >>> c.compare_signal(-1, 2) |

4286 | n/a | Decimal('-1') |

4287 | n/a | >>> c.compare_signal(Decimal(-1), 2) |

4288 | n/a | Decimal('-1') |

4289 | n/a | >>> c.compare_signal(-1, Decimal(2)) |

4290 | n/a | Decimal('-1') |

4291 | n/a | """ |

4292 | n/a | a = _convert_other(a, raiseit=True) |

4293 | n/a | return a.compare_signal(b, context=self) |

4294 | n/a | |

4295 | n/a | def compare_total(self, a, b): |

4296 | n/a | """Compares two operands using their abstract representation. |

4297 | n/a | |

4298 | n/a | This is not like the standard compare, which use their numerical |

4299 | n/a | value. Note that a total ordering is defined for all possible abstract |

4300 | n/a | representations. |

4301 | n/a | |

4302 | n/a | >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) |

4303 | n/a | Decimal('-1') |

4304 | n/a | >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) |

4305 | n/a | Decimal('-1') |

4306 | n/a | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) |

4307 | n/a | Decimal('-1') |

4308 | n/a | >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) |

4309 | n/a | Decimal('0') |

4310 | n/a | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) |

4311 | n/a | Decimal('1') |

4312 | n/a | >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) |

4313 | n/a | Decimal('-1') |

4314 | n/a | >>> ExtendedContext.compare_total(1, 2) |

4315 | n/a | Decimal('-1') |

4316 | n/a | >>> ExtendedContext.compare_total(Decimal(1), 2) |

4317 | n/a | Decimal('-1') |

4318 | n/a | >>> ExtendedContext.compare_total(1, Decimal(2)) |

4319 | n/a | Decimal('-1') |

4320 | n/a | """ |

4321 | n/a | a = _convert_other(a, raiseit=True) |

4322 | n/a | return a.compare_total(b) |

4323 | n/a | |

4324 | n/a | def compare_total_mag(self, a, b): |

4325 | n/a | """Compares two operands using their abstract representation ignoring sign. |

4326 | n/a | |

4327 | n/a | Like compare_total, but with operand's sign ignored and assumed to be 0. |

4328 | n/a | """ |

4329 | n/a | a = _convert_other(a, raiseit=True) |

4330 | n/a | return a.compare_total_mag(b) |

4331 | n/a | |

4332 | n/a | def copy_abs(self, a): |

4333 | n/a | """Returns a copy of the operand with the sign set to 0. |

4334 | n/a | |

4335 | n/a | >>> ExtendedContext.copy_abs(Decimal('2.1')) |

4336 | n/a | Decimal('2.1') |

4337 | n/a | >>> ExtendedContext.copy_abs(Decimal('-100')) |

4338 | n/a | Decimal('100') |

4339 | n/a | >>> ExtendedContext.copy_abs(-1) |

4340 | n/a | Decimal('1') |

4341 | n/a | """ |

4342 | n/a | a = _convert_other(a, raiseit=True) |

4343 | n/a | return a.copy_abs() |

4344 | n/a | |

4345 | n/a | def copy_decimal(self, a): |

4346 | n/a | """Returns a copy of the decimal object. |

4347 | n/a | |

4348 | n/a | >>> ExtendedContext.copy_decimal(Decimal('2.1')) |

4349 | n/a | Decimal('2.1') |

4350 | n/a | >>> ExtendedContext.copy_decimal(Decimal('-1.00')) |

4351 | n/a | Decimal('-1.00') |

4352 | n/a | >>> ExtendedContext.copy_decimal(1) |

4353 | n/a | Decimal('1') |

4354 | n/a | """ |

4355 | n/a | a = _convert_other(a, raiseit=True) |

4356 | n/a | return Decimal(a) |

4357 | n/a | |

4358 | n/a | def copy_negate(self, a): |

4359 | n/a | """Returns a copy of the operand with the sign inverted. |

4360 | n/a | |

4361 | n/a | >>> ExtendedContext.copy_negate(Decimal('101.5')) |

4362 | n/a | Decimal('-101.5') |

4363 | n/a | >>> ExtendedContext.copy_negate(Decimal('-101.5')) |

4364 | n/a | Decimal('101.5') |

4365 | n/a | >>> ExtendedContext.copy_negate(1) |

4366 | n/a | Decimal('-1') |

4367 | n/a | """ |

4368 | n/a | a = _convert_other(a, raiseit=True) |

4369 | n/a | return a.copy_negate() |

4370 | n/a | |

4371 | n/a | def copy_sign(self, a, b): |

4372 | n/a | """Copies the second operand's sign to the first one. |

4373 | n/a | |

4374 | n/a | In detail, it returns a copy of the first operand with the sign |

4375 | n/a | equal to the sign of the second operand. |

4376 | n/a | |

4377 | n/a | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) |

4378 | n/a | Decimal('1.50') |

4379 | n/a | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) |

4380 | n/a | Decimal('1.50') |

4381 | n/a | >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) |

4382 | n/a | Decimal('-1.50') |

4383 | n/a | >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) |

4384 | n/a | Decimal('-1.50') |

4385 | n/a | >>> ExtendedContext.copy_sign(1, -2) |

4386 | n/a | Decimal('-1') |

4387 | n/a | >>> ExtendedContext.copy_sign(Decimal(1), -2) |

4388 | n/a | Decimal('-1') |

4389 | n/a | >>> ExtendedContext.copy_sign(1, Decimal(-2)) |

4390 | n/a | Decimal('-1') |

4391 | n/a | """ |

4392 | n/a | a = _convert_other(a, raiseit=True) |

4393 | n/a | return a.copy_sign(b) |

4394 | n/a | |

4395 | n/a | def divide(self, a, b): |

4396 | n/a | """Decimal division in a specified context. |

4397 | n/a | |

4398 | n/a | >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) |

4399 | n/a | Decimal('0.333333333') |

4400 | n/a | >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) |

4401 | n/a | Decimal('0.666666667') |

4402 | n/a | >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) |

4403 | n/a | Decimal('2.5') |

4404 | n/a | >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) |

4405 | n/a | Decimal('0.1') |

4406 | n/a | >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) |

4407 | n/a | Decimal('1') |

4408 | n/a | >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) |

4409 | n/a | Decimal('4.00') |

4410 | n/a | >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) |

4411 | n/a | Decimal('1.20') |

4412 | n/a | >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) |

4413 | n/a | Decimal('10') |

4414 | n/a | >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) |

4415 | n/a | Decimal('1000') |

4416 | n/a | >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) |

4417 | n/a | Decimal('1.20E+6') |

4418 | n/a | >>> ExtendedContext.divide(5, 5) |

4419 | n/a | Decimal('1') |

4420 | n/a | >>> ExtendedContext.divide(Decimal(5), 5) |

4421 | n/a | Decimal('1') |

4422 | n/a | >>> ExtendedContext.divide(5, Decimal(5)) |

4423 | n/a | Decimal('1') |

4424 | n/a | """ |

4425 | n/a | a = _convert_other(a, raiseit=True) |

4426 | n/a | r = a.__truediv__(b, context=self) |

4427 | n/a | if r is NotImplemented: |

4428 | n/a | raise TypeError("Unable to convert %s to Decimal" % b) |

4429 | n/a | else: |

4430 | n/a | return r |

4431 | n/a | |

4432 | n/a | def divide_int(self, a, b): |

4433 | n/a | """Divides two numbers and returns the integer part of the result. |

4434 | n/a | |

4435 | n/a | >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) |

4436 | n/a | Decimal('0') |

4437 | n/a | >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) |

4438 | n/a | Decimal('3') |

4439 | n/a | >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) |

4440 | n/a | Decimal('3') |

4441 | n/a | >>> ExtendedContext.divide_int(10, 3) |

4442 | n/a | Decimal('3') |

4443 | n/a | >>> ExtendedContext.divide_int(Decimal(10), 3) |

4444 | n/a | Decimal('3') |

4445 | n/a | >>> ExtendedContext.divide_int(10, Decimal(3)) |

4446 | n/a | Decimal('3') |

4447 | n/a | """ |

4448 | n/a | a = _convert_other(a, raiseit=True) |

4449 | n/a | r = a.__floordiv__(b, context=self) |

4450 | n/a | if r is NotImplemented: |

4451 | n/a | raise TypeError("Unable to convert %s to Decimal" % b) |

4452 | n/a | else: |

4453 | n/a | return r |

4454 | n/a | |

4455 | n/a | def divmod(self, a, b): |

4456 | n/a | """Return (a // b, a % b). |

4457 | n/a | |

4458 | n/a | >>> ExtendedContext.divmod(Decimal(8), Decimal(3)) |

4459 | n/a | (Decimal('2'), Decimal('2')) |

4460 | n/a | >>> ExtendedContext.divmod(Decimal(8), Decimal(4)) |

4461 | n/a | (Decimal('2'), Decimal('0')) |

4462 | n/a | >>> ExtendedContext.divmod(8, 4) |

4463 | n/a | (Decimal('2'), Decimal('0')) |

4464 | n/a | >>> ExtendedContext.divmod(Decimal(8), 4) |

4465 | n/a | (Decimal('2'), Decimal('0')) |

4466 | n/a | >>> ExtendedContext.divmod(8, Decimal(4)) |

4467 | n/a | (Decimal('2'), Decimal('0')) |

4468 | n/a | """ |

4469 | n/a | a = _convert_other(a, raiseit=True) |

4470 | n/a | r = a.__divmod__(b, context=self) |

4471 | n/a | if r is NotImplemented: |

4472 | n/a | raise TypeError("Unable to convert %s to Decimal" % b) |

4473 | n/a | else: |

4474 | n/a | return r |

4475 | n/a | |

4476 | n/a | def exp(self, a): |

4477 | n/a | """Returns e ** a. |

4478 | n/a | |

4479 | n/a | >>> c = ExtendedContext.copy() |

4480 | n/a | >>> c.Emin = -999 |

4481 | n/a | >>> c.Emax = 999 |

4482 | n/a | >>> c.exp(Decimal('-Infinity')) |

4483 | n/a | Decimal('0') |

4484 | n/a | >>> c.exp(Decimal('-1')) |

4485 | n/a | Decimal('0.367879441') |

4486 | n/a | >>> c.exp(Decimal('0')) |

4487 | n/a | Decimal('1') |

4488 | n/a | >>> c.exp(Decimal('1')) |

4489 | n/a | Decimal('2.71828183') |

4490 | n/a | >>> c.exp(Decimal('0.693147181')) |

4491 | n/a | Decimal('2.00000000') |

4492 | n/a | >>> c.exp(Decimal('+Infinity')) |

4493 | n/a | Decimal('Infinity') |

4494 | n/a | >>> c.exp(10) |

4495 | n/a | Decimal('22026.4658') |

4496 | n/a | """ |

4497 | n/a | a =_convert_other(a, raiseit=True) |

4498 | n/a | return a.exp(context=self) |

4499 | n/a | |

4500 | n/a | def fma(self, a, b, c): |

4501 | n/a | """Returns a multiplied by b, plus c. |

4502 | n/a | |

4503 | n/a | The first two operands are multiplied together, using multiply, |

4504 | n/a | the third operand is then added to the result of that |

4505 | n/a | multiplication, using add, all with only one final rounding. |

4506 | n/a | |

4507 | n/a | >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) |

4508 | n/a | Decimal('22') |

4509 | n/a | >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) |

4510 | n/a | Decimal('-8') |

4511 | n/a | >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) |

4512 | n/a | Decimal('1.38435736E+12') |

4513 | n/a | >>> ExtendedContext.fma(1, 3, 4) |

4514 | n/a | Decimal('7') |

4515 | n/a | >>> ExtendedContext.fma(1, Decimal(3), 4) |

4516 | n/a | Decimal('7') |

4517 | n/a | >>> ExtendedContext.fma(1, 3, Decimal(4)) |

4518 | n/a | Decimal('7') |

4519 | n/a | """ |

4520 | n/a | a = _convert_other(a, raiseit=True) |

4521 | n/a | return a.fma(b, c, context=self) |

4522 | n/a | |

4523 | n/a | def is_canonical(self, a): |

4524 | n/a | """Return True if the operand is canonical; otherwise return False. |

4525 | n/a | |

4526 | n/a | Currently, the encoding of a Decimal instance is always |

4527 | n/a | canonical, so this method returns True for any Decimal. |

4528 | n/a | |

4529 | n/a | >>> ExtendedContext.is_canonical(Decimal('2.50')) |

4530 | n/a | True |

4531 | n/a | """ |

4532 | n/a | if not isinstance(a, Decimal): |

4533 | n/a | raise TypeError("is_canonical requires a Decimal as an argument.") |

4534 | n/a | return a.is_canonical() |

4535 | n/a | |

4536 | n/a | def is_finite(self, a): |

4537 | n/a | """Return True if the operand is finite; otherwise return False. |

4538 | n/a | |

4539 | n/a | A Decimal instance is considered finite if it is neither |

4540 | n/a | infinite nor a NaN. |

4541 | n/a | |

4542 | n/a | >>> ExtendedContext.is_finite(Decimal('2.50')) |

4543 | n/a | True |

4544 | n/a | >>> ExtendedContext.is_finite(Decimal('-0.3')) |

4545 | n/a | True |

4546 | n/a | >>> ExtendedContext.is_finite(Decimal('0')) |

4547 | n/a | True |

4548 | n/a | >>> ExtendedContext.is_finite(Decimal('Inf')) |

4549 | n/a | False |

4550 | n/a | >>> ExtendedContext.is_finite(Decimal('NaN')) |

4551 | n/a | False |

4552 | n/a | >>> ExtendedContext.is_finite(1) |

4553 | n/a | True |

4554 | n/a | """ |

4555 | n/a | a = _convert_other(a, raiseit=True) |

4556 | n/a | return a.is_finite() |

4557 | n/a | |

4558 | n/a | def is_infinite(self, a): |

4559 | n/a | """Return True if the operand is infinite; otherwise return False. |

4560 | n/a | |

4561 | n/a | >>> ExtendedContext.is_infinite(Decimal('2.50')) |

4562 | n/a | False |

4563 | n/a | >>> ExtendedContext.is_infinite(Decimal('-Inf')) |

4564 | n/a | True |

4565 | n/a | >>> ExtendedContext.is_infinite(Decimal('NaN')) |

4566 | n/a | False |

4567 | n/a | >>> ExtendedContext.is_infinite(1) |

4568 | n/a | False |

4569 | n/a | """ |

4570 | n/a | a = _convert_other(a, raiseit=True) |

4571 | n/a | return a.is_infinite() |

4572 | n/a | |

4573 | n/a | def is_nan(self, a): |

4574 | n/a | """Return True if the operand is a qNaN or sNaN; |

4575 | n/a | otherwise return False. |

4576 | n/a | |

4577 | n/a | >>> ExtendedContext.is_nan(Decimal('2.50')) |

4578 | n/a | False |

4579 | n/a | >>> ExtendedContext.is_nan(Decimal('NaN')) |

4580 | n/a | True |

4581 | n/a | >>> ExtendedContext.is_nan(Decimal('-sNaN')) |

4582 | n/a | True |

4583 | n/a | >>> ExtendedContext.is_nan(1) |

4584 | n/a | False |

4585 | n/a | """ |

4586 | n/a | a = _convert_other(a, raiseit=True) |

4587 | n/a | return a.is_nan() |

4588 | n/a | |

4589 | n/a | def is_normal(self, a): |

4590 | n/a | """Return True if the operand is a normal number; |

4591 | n/a | otherwise return False. |

4592 | n/a | |

4593 | n/a | >>> c = ExtendedContext.copy() |

4594 | n/a | >>> c.Emin = -999 |

4595 | n/a | >>> c.Emax = 999 |

4596 | n/a | >>> c.is_normal(Decimal('2.50')) |

4597 | n/a | True |

4598 | n/a | >>> c.is_normal(Decimal('0.1E-999')) |

4599 | n/a | False |

4600 | n/a | >>> c.is_normal(Decimal('0.00')) |

4601 | n/a | False |

4602 | n/a | >>> c.is_normal(Decimal('-Inf')) |

4603 | n/a | False |

4604 | n/a | >>> c.is_normal(Decimal('NaN')) |

4605 | n/a | False |

4606 | n/a | >>> c.is_normal(1) |

4607 | n/a | True |

4608 | n/a | """ |

4609 | n/a | a = _convert_other(a, raiseit=True) |

4610 | n/a | return a.is_normal(context=self) |

4611 | n/a | |

4612 | n/a | def is_qnan(self, a): |

4613 | n/a | """Return True if the operand is a quiet NaN; otherwise return False. |

4614 | n/a | |

4615 | n/a | >>> ExtendedContext.is_qnan(Decimal('2.50')) |

4616 | n/a | False |

4617 | n/a | >>> ExtendedContext.is_qnan(Decimal('NaN')) |

4618 | n/a | True |

4619 | n/a | >>> ExtendedContext.is_qnan(Decimal('sNaN')) |

4620 | n/a | False |

4621 | n/a | >>> ExtendedContext.is_qnan(1) |

4622 | n/a | False |

4623 | n/a | """ |

4624 | n/a | a = _convert_other(a, raiseit=True) |

4625 | n/a | return a.is_qnan() |

4626 | n/a | |

4627 | n/a | def is_signed(self, a): |

4628 | n/a | """Return True if the operand is negative; otherwise return False. |

4629 | n/a | |

4630 | n/a | >>> ExtendedContext.is_signed(Decimal('2.50')) |

4631 | n/a | False |

4632 | n/a | >>> ExtendedContext.is_signed(Decimal('-12')) |

4633 | n/a | True |

4634 | n/a | >>> ExtendedContext.is_signed(Decimal('-0')) |

4635 | n/a | True |

4636 | n/a | >>> ExtendedContext.is_signed(8) |

4637 | n/a | False |

4638 | n/a | >>> ExtendedContext.is_signed(-8) |

4639 | n/a | True |

4640 | n/a | """ |

4641 | n/a | a = _convert_other(a, raiseit=True) |

4642 | n/a | return a.is_signed() |

4643 | n/a | |

4644 | n/a | def is_snan(self, a): |

4645 | n/a | """Return True if the operand is a signaling NaN; |

4646 | n/a | otherwise return False. |

4647 | n/a | |

4648 | n/a | >>> ExtendedContext.is_snan(Decimal('2.50')) |

4649 | n/a | False |

4650 | n/a | >>> ExtendedContext.is_snan(Decimal('NaN')) |

4651 | n/a | False |

4652 | n/a | >>> ExtendedContext.is_snan(Decimal('sNaN')) |

4653 | n/a | True |

4654 | n/a | >>> ExtendedContext.is_snan(1) |

4655 | n/a | False |

4656 | n/a | """ |

4657 | n/a | a = _convert_other(a, raiseit=True) |

4658 | n/a | return a.is_snan() |

4659 | n/a | |

4660 | n/a | def is_subnormal(self, a): |

4661 | n/a | """Return True if the operand is subnormal; otherwise return False. |

4662 | n/a | |

4663 | n/a | >>> c = ExtendedContext.copy() |

4664 | n/a | >>> c.Emin = -999 |

4665 | n/a | >>> c.Emax = 999 |

4666 | n/a | >>> c.is_subnormal(Decimal('2.50')) |

4667 | n/a | False |

4668 | n/a | >>> c.is_subnormal(Decimal('0.1E-999')) |

4669 | n/a | True |

4670 | n/a | >>> c.is_subnormal(Decimal('0.00')) |

4671 | n/a | False |

4672 | n/a | >>> c.is_subnormal(Decimal('-Inf')) |

4673 | n/a | False |

4674 | n/a | >>> c.is_subnormal(Decimal('NaN')) |

4675 | n/a | False |

4676 | n/a | >>> c.is_subnormal(1) |

4677 | n/a | False |

4678 | n/a | """ |

4679 | n/a | a = _convert_other(a, raiseit=True) |

4680 | n/a | return a.is_subnormal(context=self) |

4681 | n/a | |

4682 | n/a | def is_zero(self, a): |

4683 | n/a | """Return True if the operand is a zero; otherwise return False. |

4684 | n/a | |

4685 | n/a | >>> ExtendedContext.is_zero(Decimal('0')) |

4686 | n/a | True |

4687 | n/a | >>> ExtendedContext.is_zero(Decimal('2.50')) |

4688 | n/a | False |

4689 | n/a | >>> ExtendedContext.is_zero(Decimal('-0E+2')) |

4690 | n/a | True |

4691 | n/a | >>> ExtendedContext.is_zero(1) |

4692 | n/a | False |

4693 | n/a | >>> ExtendedContext.is_zero(0) |

4694 | n/a | True |

4695 | n/a | """ |

4696 | n/a | a = _convert_other(a, raiseit=True) |

4697 | n/a | return a.is_zero() |

4698 | n/a | |

4699 | n/a | def ln(self, a): |

4700 | n/a | """Returns the natural (base e) logarithm of the operand. |

4701 | n/a | |

4702 | n/a | >>> c = ExtendedContext.copy() |

4703 | n/a | >>> c.Emin = -999 |

4704 | n/a | >>> c.Emax = 999 |

4705 | n/a | >>> c.ln(Decimal('0')) |

4706 | n/a | Decimal('-Infinity') |

4707 | n/a | >>> c.ln(Decimal('1.000')) |

4708 | n/a | Decimal('0') |

4709 | n/a | >>> c.ln(Decimal('2.71828183')) |

4710 | n/a | Decimal('1.00000000') |

4711 | n/a | >>> c.ln(Decimal('10')) |

4712 | n/a | Decimal('2.30258509') |

4713 | n/a | >>> c.ln(Decimal('+Infinity')) |

4714 | n/a | Decimal('Infinity') |

4715 | n/a | >>> c.ln(1) |

4716 | n/a | Decimal('0') |

4717 | n/a | """ |

4718 | n/a | a = _convert_other(a, raiseit=True) |

4719 | n/a | return a.ln(context=self) |

4720 | n/a | |

4721 | n/a | def log10(self, a): |

4722 | n/a | """Returns the base 10 logarithm of the operand. |

4723 | n/a | |

4724 | n/a | >>> c = ExtendedContext.copy() |

4725 | n/a | >>> c.Emin = -999 |

4726 | n/a | >>> c.Emax = 999 |

4727 | n/a | >>> c.log10(Decimal('0')) |

4728 | n/a | Decimal('-Infinity') |

4729 | n/a | >>> c.log10(Decimal('0.001')) |

4730 | n/a | Decimal('-3') |

4731 | n/a | >>> c.log10(Decimal('1.000')) |

4732 | n/a | Decimal('0') |

4733 | n/a | >>> c.log10(Decimal('2')) |

4734 | n/a | Decimal('0.301029996') |

4735 | n/a | >>> c.log10(Decimal('10')) |

4736 | n/a | Decimal('1') |

4737 | n/a | >>> c.log10(Decimal('70')) |

4738 | n/a | Decimal('1.84509804') |

4739 | n/a | >>> c.log10(Decimal('+Infinity')) |

4740 | n/a | Decimal('Infinity') |

4741 | n/a | >>> c.log10(0) |

4742 | n/a | Decimal('-Infinity') |

4743 | n/a | >>> c.log10(1) |

4744 | n/a | Decimal('0') |

4745 | n/a | """ |

4746 | n/a | a = _convert_other(a, raiseit=True) |

4747 | n/a | return a.log10(context=self) |

4748 | n/a | |

4749 | n/a | def logb(self, a): |

4750 | n/a | """ Returns the exponent of the magnitude of the operand's MSD. |

4751 | n/a | |

4752 | n/a | The result is the integer which is the exponent of the magnitude |

4753 | n/a | of the most significant digit of the operand (as though the |

4754 | n/a | operand were truncated to a single digit while maintaining the |

4755 | n/a | value of that digit and without limiting the resulting exponent). |

4756 | n/a | |

4757 | n/a | >>> ExtendedContext.logb(Decimal('250')) |

4758 | n/a | Decimal('2') |

4759 | n/a | >>> ExtendedContext.logb(Decimal('2.50')) |

4760 | n/a | Decimal('0') |

4761 | n/a | >>> ExtendedContext.logb(Decimal('0.03')) |

4762 | n/a | Decimal('-2') |

4763 | n/a | >>> ExtendedContext.logb(Decimal('0')) |

4764 | n/a | Decimal('-Infinity') |

4765 | n/a | >>> ExtendedContext.logb(1) |

4766 | n/a | Decimal('0') |

4767 | n/a | >>> ExtendedContext.logb(10) |

4768 | n/a | Decimal('1') |

4769 | n/a | >>> ExtendedContext.logb(100) |

4770 | n/a | Decimal('2') |

4771 | n/a | """ |

4772 | n/a | a = _convert_other(a, raiseit=True) |

4773 | n/a | return a.logb(context=self) |

4774 | n/a | |

4775 | n/a | def logical_and(self, a, b): |

4776 | n/a | """Applies the logical operation 'and' between each operand's digits. |

4777 | n/a | |

4778 | n/a | The operands must be both logical numbers. |

4779 | n/a | |

4780 | n/a | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) |

4781 | n/a | Decimal('0') |

4782 | n/a | >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) |

4783 | n/a | Decimal('0') |

4784 | n/a | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) |

4785 | n/a | Decimal('0') |

4786 | n/a | >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) |

4787 | n/a | Decimal('1') |

4788 | n/a | >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) |

4789 | n/a | Decimal('1000') |

4790 | n/a | >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) |

4791 | n/a | Decimal('10') |

4792 | n/a | >>> ExtendedContext.logical_and(110, 1101) |

4793 | n/a | Decimal('100') |

4794 | n/a | >>> ExtendedContext.logical_and(Decimal(110), 1101) |

4795 | n/a | Decimal('100') |

4796 | n/a | >>> ExtendedContext.logical_and(110, Decimal(1101)) |

4797 | n/a | Decimal('100') |

4798 | n/a | """ |

4799 | n/a | a = _convert_other(a, raiseit=True) |

4800 | n/a | return a.logical_and(b, context=self) |

4801 | n/a | |

4802 | n/a | def logical_invert(self, a): |

4803 | n/a | """Invert all the digits in the operand. |

4804 | n/a | |

4805 | n/a | The operand must be a logical number. |

4806 | n/a | |

4807 | n/a | >>> ExtendedContext.logical_invert(Decimal('0')) |

4808 | n/a | Decimal('111111111') |

4809 | n/a | >>> ExtendedContext.logical_invert(Decimal('1')) |

4810 | n/a | Decimal('111111110') |

4811 | n/a | >>> ExtendedContext.logical_invert(Decimal('111111111')) |

4812 | n/a | Decimal('0') |

4813 | n/a | >>> ExtendedContext.logical_invert(Decimal('101010101')) |

4814 | n/a | Decimal('10101010') |

4815 | n/a | >>> ExtendedContext.logical_invert(1101) |

4816 | n/a | Decimal('111110010') |

4817 | n/a | """ |

4818 | n/a | a = _convert_other(a, raiseit=True) |

4819 | n/a | return a.logical_invert(context=self) |

4820 | n/a | |

4821 | n/a | def logical_or(self, a, b): |

4822 | n/a | """Applies the logical operation 'or' between each operand's digits. |

4823 | n/a | |

4824 | n/a | The operands must be both logical numbers. |

4825 | n/a | |

4826 | n/a | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) |

4827 | n/a | Decimal('0') |

4828 | n/a | >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) |

4829 | n/a | Decimal('1') |

4830 | n/a | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) |

4831 | n/a | Decimal('1') |

4832 | n/a | >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) |

4833 | n/a | Decimal('1') |

4834 | n/a | >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) |

4835 | n/a | Decimal('1110') |

4836 | n/a | >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) |

4837 | n/a | Decimal('1110') |

4838 | n/a | >>> ExtendedContext.logical_or(110, 1101) |

4839 | n/a | Decimal('1111') |

4840 | n/a | >>> ExtendedContext.logical_or(Decimal(110), 1101) |

4841 | n/a | Decimal('1111') |

4842 | n/a | >>> ExtendedContext.logical_or(110, Decimal(1101)) |

4843 | n/a | Decimal('1111') |

4844 | n/a | """ |

4845 | n/a | a = _convert_other(a, raiseit=True) |

4846 | n/a | return a.logical_or(b, context=self) |

4847 | n/a | |

4848 | n/a | def logical_xor(self, a, b): |

4849 | n/a | """Applies the logical operation 'xor' between each operand's digits. |

4850 | n/a | |

4851 | n/a | The operands must be both logical numbers. |

4852 | n/a | |

4853 | n/a | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) |

4854 | n/a | Decimal('0') |

4855 | n/a | >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) |

4856 | n/a | Decimal('1') |

4857 | n/a | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) |

4858 | n/a | Decimal('1') |

4859 | n/a | >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) |

4860 | n/a | Decimal('0') |

4861 | n/a | >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) |

4862 | n/a | Decimal('110') |

4863 | n/a | >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) |

4864 | n/a | Decimal('1101') |

4865 | n/a | >>> ExtendedContext.logical_xor(110, 1101) |

4866 | n/a | Decimal('1011') |

4867 | n/a | >>> ExtendedContext.logical_xor(Decimal(110), 1101) |

4868 | n/a | Decimal('1011') |

4869 | n/a | >>> ExtendedContext.logical_xor(110, Decimal(1101)) |

4870 | n/a | Decimal('1011') |

4871 | n/a | """ |

4872 | n/a | a = _convert_other(a, raiseit=True) |

4873 | n/a | return a.logical_xor(b, context=self) |

4874 | n/a | |

4875 | n/a | def max(self, a, b): |

4876 | n/a | """max compares two values numerically and returns the maximum. |

4877 | n/a | |

4878 | n/a | If either operand is a NaN then the general rules apply. |

4879 | n/a | Otherwise, the operands are compared as though by the compare |

4880 | n/a | operation. If they are numerically equal then the left-hand operand |

4881 | n/a | is chosen as the result. Otherwise the maximum (closer to positive |

4882 | n/a | infinity) of the two operands is chosen as the result. |

4883 | n/a | |

4884 | n/a | >>> ExtendedContext.max(Decimal('3'), Decimal('2')) |

4885 | n/a | Decimal('3') |

4886 | n/a | >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) |

4887 | n/a | Decimal('3') |

4888 | n/a | >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) |

4889 | n/a | Decimal('1') |

4890 | n/a | >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) |

4891 | n/a | Decimal('7') |

4892 | n/a | >>> ExtendedContext.max(1, 2) |

4893 | n/a | Decimal('2') |

4894 | n/a | >>> ExtendedContext.max(Decimal(1), 2) |

4895 | n/a | Decimal('2') |

4896 | n/a | >>> ExtendedContext.max(1, Decimal(2)) |

4897 | n/a | Decimal('2') |

4898 | n/a | """ |

4899 | n/a | a = _convert_other(a, raiseit=True) |

4900 | n/a | return a.max(b, context=self) |

4901 | n/a | |

4902 | n/a | def max_mag(self, a, b): |

4903 | n/a | """Compares the values numerically with their sign ignored. |

4904 | n/a | |

4905 | n/a | >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN')) |

4906 | n/a | Decimal('7') |

4907 | n/a | >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10')) |

4908 | n/a | Decimal('-10') |

4909 | n/a | >>> ExtendedContext.max_mag(1, -2) |

4910 | n/a | Decimal('-2') |

4911 | n/a | >>> ExtendedContext.max_mag(Decimal(1), -2) |

4912 | n/a | Decimal('-2') |

4913 | n/a | >>> ExtendedContext.max_mag(1, Decimal(-2)) |

4914 | n/a | Decimal('-2') |

4915 | n/a | """ |

4916 | n/a | a = _convert_other(a, raiseit=True) |

4917 | n/a | return a.max_mag(b, context=self) |

4918 | n/a | |

4919 | n/a | def min(self, a, b): |

4920 | n/a | """min compares two values numerically and returns the minimum. |

4921 | n/a | |

4922 | n/a | If either operand is a NaN then the general rules apply. |

4923 | n/a | Otherwise, the operands are compared as though by the compare |

4924 | n/a | operation. If they are numerically equal then the left-hand operand |

4925 | n/a | is chosen as the result. Otherwise the minimum (closer to negative |

4926 | n/a | infinity) of the two operands is chosen as the result. |

4927 | n/a | |

4928 | n/a | >>> ExtendedContext.min(Decimal('3'), Decimal('2')) |

4929 | n/a | Decimal('2') |

4930 | n/a | >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) |

4931 | n/a | Decimal('-10') |

4932 | n/a | >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) |

4933 | n/a | Decimal('1.0') |

4934 | n/a | >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) |

4935 | n/a | Decimal('7') |

4936 | n/a | >>> ExtendedContext.min(1, 2) |

4937 | n/a | Decimal('1') |

4938 | n/a | >>> ExtendedContext.min(Decimal(1), 2) |

4939 | n/a | Decimal('1') |

4940 | n/a | >>> ExtendedContext.min(1, Decimal(29)) |

4941 | n/a | Decimal('1') |

4942 | n/a | """ |

4943 | n/a | a = _convert_other(a, raiseit=True) |

4944 | n/a | return a.min(b, context=self) |

4945 | n/a | |

4946 | n/a | def min_mag(self, a, b): |

4947 | n/a | """Compares the values numerically with their sign ignored. |

4948 | n/a | |

4949 | n/a | >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2')) |

4950 | n/a | Decimal('-2') |

4951 | n/a | >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN')) |

4952 | n/a | Decimal('-3') |

4953 | n/a | >>> ExtendedContext.min_mag(1, -2) |

4954 | n/a | Decimal('1') |

4955 | n/a | >>> ExtendedContext.min_mag(Decimal(1), -2) |

4956 | n/a | Decimal('1') |

4957 | n/a | >>> ExtendedContext.min_mag(1, Decimal(-2)) |

4958 | n/a | Decimal('1') |

4959 | n/a | """ |

4960 | n/a | a = _convert_other(a, raiseit=True) |

4961 | n/a | return a.min_mag(b, context=self) |

4962 | n/a | |

4963 | n/a | def minus(self, a): |

4964 | n/a | """Minus corresponds to unary prefix minus in Python. |

4965 | n/a | |

4966 | n/a | The operation is evaluated using the same rules as subtract; the |

4967 | n/a | operation minus(a) is calculated as subtract('0', a) where the '0' |

4968 | n/a | has the same exponent as the operand. |

4969 | n/a | |

4970 | n/a | >>> ExtendedContext.minus(Decimal('1.3')) |

4971 | n/a | Decimal('-1.3') |

4972 | n/a | >>> ExtendedContext.minus(Decimal('-1.3')) |

4973 | n/a | Decimal('1.3') |

4974 | n/a | >>> ExtendedContext.minus(1) |

4975 | n/a | Decimal('-1') |

4976 | n/a | """ |

4977 | n/a | a = _convert_other(a, raiseit=True) |

4978 | n/a | return a.__neg__(context=self) |

4979 | n/a | |

4980 | n/a | def multiply(self, a, b): |

4981 | n/a | """multiply multiplies two operands. |

4982 | n/a | |

4983 | n/a | If either operand is a special value then the general rules apply. |

4984 | n/a | Otherwise, the operands are multiplied together |

4985 | n/a | ('long multiplication'), resulting in a number which may be as long as |

4986 | n/a | the sum of the lengths of the two operands. |

4987 | n/a | |

4988 | n/a | >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) |

4989 | n/a | Decimal('3.60') |

4990 | n/a | >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) |

4991 | n/a | Decimal('21') |

4992 | n/a | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) |

4993 | n/a | Decimal('0.72') |

4994 | n/a | >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) |

4995 | n/a | Decimal('-0.0') |

4996 | n/a | >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) |

4997 | n/a | Decimal('4.28135971E+11') |

4998 | n/a | >>> ExtendedContext.multiply(7, 7) |

4999 | n/a | Decimal('49') |

5000 | n/a | >>> ExtendedContext.multiply(Decimal(7), 7) |

5001 | n/a | Decimal('49') |

5002 | n/a | >>> ExtendedContext.multiply(7, Decimal(7)) |

5003 | n/a | Decimal('49') |

5004 | n/a | """ |

5005 | n/a | a = _convert_other(a, raiseit=True) |

5006 | n/a | r = a.__mul__(b, context=self) |

5007 | n/a | if r is NotImplemented: |

5008 | n/a | raise TypeError("Unable to convert %s to Decimal" % b) |

5009 | n/a | else: |

5010 | n/a | return r |

5011 | n/a | |

5012 | n/a | def next_minus(self, a): |

5013 | n/a | """Returns the largest representable number smaller than a. |

5014 | n/a | |

5015 | n/a | >>> c = ExtendedContext.copy() |

5016 | n/a | >>> c.Emin = -999 |

5017 | n/a | >>> c.Emax = 999 |

5018 | n/a | >>> ExtendedContext.next_minus(Decimal('1')) |

5019 | n/a | Decimal('0.999999999') |

5020 | n/a | >>> c.next_minus(Decimal('1E-1007')) |

5021 | n/a | Decimal('0E-1007') |

5022 | n/a | >>> ExtendedContext.next_minus(Decimal('-1.00000003')) |

5023 | n/a | Decimal('-1.00000004') |

5024 | n/a | >>> c.next_minus(Decimal('Infinity')) |

5025 | n/a | Decimal('9.99999999E+999') |

5026 | n/a | >>> c.next_minus(1) |

5027 | n/a | Decimal('0.999999999') |

5028 | n/a | """ |

5029 | n/a | a = _convert_other(a, raiseit=True) |

5030 | n/a | return a.next_minus(context=self) |

5031 | n/a | |

5032 | n/a | def next_plus(self, a): |

5033 | n/a | """Returns the smallest representable number larger than a. |

5034 | n/a | |

5035 | n/a | >>> c = ExtendedContext.copy() |

5036 | n/a | >>> c.Emin = -999 |

5037 | n/a | >>> c.Emax = 999 |

5038 | n/a | >>> ExtendedContext.next_plus(Decimal('1')) |

5039 | n/a | Decimal('1.00000001') |

5040 | n/a | >>> c.next_plus(Decimal('-1E-1007')) |

5041 | n/a | Decimal('-0E-1007') |

5042 | n/a | >>> ExtendedContext.next_plus(Decimal('-1.00000003')) |

5043 | n/a | Decimal('-1.00000002') |

5044 | n/a | >>> c.next_plus(Decimal('-Infinity')) |

5045 | n/a | Decimal('-9.99999999E+999') |

5046 | n/a | >>> c.next_plus(1) |

5047 | n/a | Decimal('1.00000001') |

5048 | n/a | """ |

5049 | n/a | a = _convert_other(a, raiseit=True) |

5050 | n/a | return a.next_plus(context=self) |

5051 | n/a | |

5052 | n/a | def next_toward(self, a, b): |

5053 | n/a | """Returns the number closest to a, in direction towards b. |

5054 | n/a | |

5055 | n/a | The result is the closest representable number from the first |

5056 | n/a | operand (but not the first operand) that is in the direction |

5057 | n/a | towards the second operand, unless the operands have the same |

5058 | n/a | value. |

5059 | n/a | |

5060 | n/a | >>> c = ExtendedContext.copy() |

5061 | n/a | >>> c.Emin = -999 |

5062 | n/a | >>> c.Emax = 999 |

5063 | n/a | >>> c.next_toward(Decimal('1'), Decimal('2')) |

5064 | n/a | Decimal('1.00000001') |

5065 | n/a | >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) |

5066 | n/a | Decimal('-0E-1007') |

5067 | n/a | >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) |

5068 | n/a | Decimal('-1.00000002') |

5069 | n/a | >>> c.next_toward(Decimal('1'), Decimal('0')) |

5070 | n/a | Decimal('0.999999999') |

5071 | n/a | >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) |

5072 | n/a | Decimal('0E-1007') |

5073 | n/a | >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) |

5074 | n/a | Decimal('-1.00000004') |

5075 | n/a | >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) |

5076 | n/a | Decimal('-0.00') |

5077 | n/a | >>> c.next_toward(0, 1) |

5078 | n/a | Decimal('1E-1007') |

5079 | n/a | >>> c.next_toward(Decimal(0), 1) |

5080 | n/a | Decimal('1E-1007') |

5081 | n/a | >>> c.next_toward(0, Decimal(1)) |

5082 | n/a | Decimal('1E-1007') |

5083 | n/a | """ |

5084 | n/a | a = _convert_other(a, raiseit=True) |

5085 | n/a | return a.next_toward(b, context=self) |

5086 | n/a | |

5087 | n/a | def normalize(self, a): |

5088 | n/a | """normalize reduces an operand to its simplest form. |

5089 | n/a | |

5090 | n/a | Essentially a plus operation with all trailing zeros removed from the |

5091 | n/a | result. |

5092 | n/a | |

5093 | n/a | >>> ExtendedContext.normalize(Decimal('2.1')) |

5094 | n/a | Decimal('2.1') |

5095 | n/a | >>> ExtendedContext.normalize(Decimal('-2.0')) |

5096 | n/a | Decimal('-2') |

5097 | n/a | >>> ExtendedContext.normalize(Decimal('1.200')) |

5098 | n/a | Decimal('1.2') |

5099 | n/a | >>> ExtendedContext.normalize(Decimal('-120')) |

5100 | n/a | Decimal('-1.2E+2') |

5101 | n/a | >>> ExtendedContext.normalize(Decimal('120.00')) |

5102 | n/a | Decimal('1.2E+2') |

5103 | n/a | >>> ExtendedContext.normalize(Decimal('0.00')) |

5104 | n/a | Decimal('0') |

5105 | n/a | >>> ExtendedContext.normalize(6) |

5106 | n/a | Decimal('6') |

5107 | n/a | """ |

5108 | n/a | a = _convert_other(a, raiseit=True) |

5109 | n/a | return a.normalize(context=self) |

5110 | n/a | |

5111 | n/a | def number_class(self, a): |

5112 | n/a | """Returns an indication of the class of the operand. |

5113 | n/a | |

5114 | n/a | The class is one of the following strings: |

5115 | n/a | -sNaN |

5116 | n/a | -NaN |

5117 | n/a | -Infinity |

5118 | n/a | -Normal |

5119 | n/a | -Subnormal |

5120 | n/a | -Zero |

5121 | n/a | +Zero |

5122 | n/a | +Subnormal |

5123 | n/a | +Normal |

5124 | n/a | +Infinity |

5125 | n/a | |

5126 | n/a | >>> c = ExtendedContext.copy() |

5127 | n/a | >>> c.Emin = -999 |

5128 | n/a | >>> c.Emax = 999 |

5129 | n/a | >>> c.number_class(Decimal('Infinity')) |

5130 | n/a | '+Infinity' |

5131 | n/a | >>> c.number_class(Decimal('1E-10')) |

5132 | n/a | '+Normal' |

5133 | n/a | >>> c.number_class(Decimal('2.50')) |

5134 | n/a | '+Normal' |

5135 | n/a | >>> c.number_class(Decimal('0.1E-999')) |

5136 | n/a | '+Subnormal' |

5137 | n/a | >>> c.number_class(Decimal('0')) |

5138 | n/a | '+Zero' |

5139 | n/a | >>> c.number_class(Decimal('-0')) |

5140 | n/a | '-Zero' |

5141 | n/a | >>> c.number_class(Decimal('-0.1E-999')) |

5142 | n/a | '-Subnormal' |

5143 | n/a | >>> c.number_class(Decimal('-1E-10')) |

5144 | n/a | '-Normal' |

5145 | n/a | >>> c.number_class(Decimal('-2.50')) |

5146 | n/a | '-Normal' |

5147 | n/a | >>> c.number_class(Decimal('-Infinity')) |

5148 | n/a | '-Infinity' |

5149 | n/a | >>> c.number_class(Decimal('NaN')) |

5150 | n/a | 'NaN' |

5151 | n/a | >>> c.number_class(Decimal('-NaN')) |

5152 | n/a | 'NaN' |

5153 | n/a | >>> c.number_class(Decimal('sNaN')) |

5154 | n/a | 'sNaN' |

5155 | n/a | >>> c.number_class(123) |

5156 | n/a | '+Normal' |

5157 | n/a | """ |

5158 | n/a | a = _convert_other(a, raiseit=True) |

5159 | n/a | return a.number_class(context=self) |

5160 | n/a | |

5161 | n/a | def plus(self, a): |

5162 | n/a | """Plus corresponds to unary prefix plus in Python. |

5163 | n/a | |

5164 | n/a | The operation is evaluated using the same rules as add; the |

5165 | n/a | operation plus(a) is calculated as add('0', a) where the '0' |

5166 | n/a | has the same exponent as the operand. |

5167 | n/a | |

5168 | n/a | >>> ExtendedContext.plus(Decimal('1.3')) |

5169 | n/a | Decimal('1.3') |

5170 | n/a | >>> ExtendedContext.plus(Decimal('-1.3')) |

5171 | n/a | Decimal('-1.3') |

5172 | n/a | >>> ExtendedContext.plus(-1) |

5173 | n/a | Decimal('-1') |

5174 | n/a | """ |

5175 | n/a | a = _convert_other(a, raiseit=True) |

5176 | n/a | return a.__pos__(context=self) |

5177 | n/a | |

5178 | n/a | def power(self, a, b, modulo=None): |

5179 | n/a | """Raises a to the power of b, to modulo if given. |

5180 | n/a | |

5181 | n/a | With two arguments, compute a**b. If a is negative then b |

5182 | n/a | must be integral. The result will be inexact unless b is |

5183 | n/a | integral and the result is finite and can be expressed exactly |

5184 | n/a | in 'precision' digits. |

5185 | n/a | |

5186 | n/a | With three arguments, compute (a**b) % modulo. For the |

5187 | n/a | three argument form, the following restrictions on the |

5188 | n/a | arguments hold: |

5189 | n/a | |

5190 | n/a | - all three arguments must be integral |

5191 | n/a | - b must be nonnegative |

5192 | n/a | - at least one of a or b must be nonzero |

5193 | n/a | - modulo must be nonzero and have at most 'precision' digits |

5194 | n/a | |

5195 | n/a | The result of pow(a, b, modulo) is identical to the result |

5196 | n/a | that would be obtained by computing (a**b) % modulo with |

5197 | n/a | unbounded precision, but is computed more efficiently. It is |

5198 | n/a | always exact. |

5199 | n/a | |

5200 | n/a | >>> c = ExtendedContext.copy() |

5201 | n/a | >>> c.Emin = -999 |

5202 | n/a | >>> c.Emax = 999 |

5203 | n/a | >>> c.power(Decimal('2'), Decimal('3')) |

5204 | n/a | Decimal('8') |

5205 | n/a | >>> c.power(Decimal('-2'), Decimal('3')) |

5206 | n/a | Decimal('-8') |

5207 | n/a | >>> c.power(Decimal('2'), Decimal('-3')) |

5208 | n/a | Decimal('0.125') |

5209 | n/a | >>> c.power(Decimal('1.7'), Decimal('8')) |

5210 | n/a | Decimal('69.7575744') |

5211 | n/a | >>> c.power(Decimal('10'), Decimal('0.301029996')) |

5212 | n/a | Decimal('2.00000000') |

5213 | n/a | >>> c.power(Decimal('Infinity'), Decimal('-1')) |

5214 | n/a | Decimal('0') |

5215 | n/a | >>> c.power(Decimal('Infinity'), Decimal('0')) |

5216 | n/a | Decimal('1') |

5217 | n/a | >>> c.power(Decimal('Infinity'), Decimal('1')) |

5218 | n/a | Decimal('Infinity') |

5219 | n/a | >>> c.power(Decimal('-Infinity'), Decimal('-1')) |

5220 | n/a | Decimal('-0') |

5221 | n/a | >>> c.power(Decimal('-Infinity'), Decimal('0')) |

5222 | n/a | Decimal('1') |

5223 | n/a | >>> c.power(Decimal('-Infinity'), Decimal('1')) |

5224 | n/a | Decimal('-Infinity') |

5225 | n/a | >>> c.power(Decimal('-Infinity'), Decimal('2')) |

5226 | n/a | Decimal('Infinity') |

5227 | n/a | >>> c.power(Decimal('0'), Decimal('0')) |

5228 | n/a | Decimal('NaN') |

5229 | n/a | |

5230 | n/a | >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) |

5231 | n/a | Decimal('11') |

5232 | n/a | >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) |

5233 | n/a | Decimal('-11') |

5234 | n/a | >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) |

5235 | n/a | Decimal('1') |

5236 | n/a | >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) |

5237 | n/a | Decimal('11') |

5238 | n/a | >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) |

5239 | n/a | Decimal('11729830') |

5240 | n/a | >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) |

5241 | n/a | Decimal('-0') |

5242 | n/a | >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) |

5243 | n/a | Decimal('1') |

5244 | n/a | >>> ExtendedContext.power(7, 7) |

5245 | n/a | Decimal('823543') |

5246 | n/a | >>> ExtendedContext.power(Decimal(7), 7) |

5247 | n/a | Decimal('823543') |

5248 | n/a | >>> ExtendedContext.power(7, Decimal(7), 2) |

5249 | n/a | Decimal('1') |

5250 | n/a | """ |

5251 | n/a | a = _convert_other(a, raiseit=True) |

5252 | n/a | r = a.__pow__(b, modulo, context=self) |

5253 | n/a | if r is NotImplemented: |

5254 | n/a | raise TypeError("Unable to convert %s to Decimal" % b) |

5255 | n/a | else: |

5256 | n/a | return r |

5257 | n/a | |

5258 | n/a | def quantize(self, a, b): |

5259 | n/a | """Returns a value equal to 'a' (rounded), having the exponent of 'b'. |

5260 | n/a | |

5261 | n/a | The coefficient of the result is derived from that of the left-hand |

5262 | n/a | operand. It may be rounded using the current rounding setting (if the |

5263 | n/a | exponent is being increased), multiplied by a positive power of ten (if |

5264 | n/a | the exponent is being decreased), or is unchanged (if the exponent is |

5265 | n/a | already equal to that of the right-hand operand). |

5266 | n/a | |

5267 | n/a | Unlike other operations, if the length of the coefficient after the |

5268 | n/a | quantize operation would be greater than precision then an Invalid |

5269 | n/a | operation condition is raised. This guarantees that, unless there is |

5270 | n/a | an error condition, the exponent of the result of a quantize is always |

5271 | n/a | equal to that of the right-hand operand. |

5272 | n/a | |

5273 | n/a | Also unlike other operations, quantize will never raise Underflow, even |

5274 | n/a | if the result is subnormal and inexact. |

5275 | n/a | |

5276 | n/a | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) |

5277 | n/a | Decimal('2.170') |

5278 | n/a | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) |

5279 | n/a | Decimal('2.17') |

5280 | n/a | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) |

5281 | n/a | Decimal('2.2') |

5282 | n/a | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) |

5283 | n/a | Decimal('2') |

5284 | n/a | >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) |

5285 | n/a | Decimal('0E+1') |

5286 | n/a | >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) |

5287 | n/a | Decimal('-Infinity') |

5288 | n/a | >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) |

5289 | n/a | Decimal('NaN') |

5290 | n/a | >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) |

5291 | n/a | Decimal('-0') |

5292 | n/a | >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) |

5293 | n/a | Decimal('-0E+5') |

5294 | n/a | >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) |

5295 | n/a | Decimal('NaN') |

5296 | n/a | >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) |

5297 | n/a | Decimal('NaN') |

5298 | n/a | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) |

5299 | n/a | Decimal('217.0') |

5300 | n/a | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) |

5301 | n/a | Decimal('217') |

5302 | n/a | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) |

5303 | n/a | Decimal('2.2E+2') |

5304 | n/a | >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) |

5305 | n/a | Decimal('2E+2') |

5306 | n/a | >>> ExtendedContext.quantize(1, 2) |

5307 | n/a | Decimal('1') |

5308 | n/a | >>> ExtendedContext.quantize(Decimal(1), 2) |

5309 | n/a | Decimal('1') |

5310 | n/a | >>> ExtendedContext.quantize(1, Decimal(2)) |

5311 | n/a | Decimal('1') |

5312 | n/a | """ |

5313 | n/a | a = _convert_other(a, raiseit=True) |

5314 | n/a | return a.quantize(b, context=self) |

5315 | n/a | |

5316 | n/a | def radix(self): |

5317 | n/a | """Just returns 10, as this is Decimal, :) |

5318 | n/a | |

5319 | n/a | >>> ExtendedContext.radix() |

5320 | n/a | Decimal('10') |

5321 | n/a | """ |

5322 | n/a | return Decimal(10) |

5323 | n/a | |

5324 | n/a | def remainder(self, a, b): |

5325 | n/a | """Returns the remainder from integer division. |

5326 | n/a | |

5327 | n/a | The result is the residue of the dividend after the operation of |

5328 | n/a | calculating integer division as described for divide-integer, rounded |

5329 | n/a | to precision digits if necessary. The sign of the result, if |

5330 | n/a | non-zero, is the same as that of the original dividend. |

5331 | n/a | |

5332 | n/a | This operation will fail under the same conditions as integer division |

5333 | n/a | (that is, if integer division on the same two operands would fail, the |

5334 | n/a | remainder cannot be calculated). |

5335 | n/a | |

5336 | n/a | >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) |

5337 | n/a | Decimal('2.1') |

5338 | n/a | >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) |

5339 | n/a | Decimal('1') |

5340 | n/a | >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) |

5341 | n/a | Decimal('-1') |

5342 | n/a | >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) |

5343 | n/a | Decimal('0.2') |

5344 | n/a | >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) |

5345 | n/a | Decimal('0.1') |

5346 | n/a | >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) |

5347 | n/a | Decimal('1.0') |

5348 | n/a | >>> ExtendedContext.remainder(22, 6) |

5349 | n/a | Decimal('4') |

5350 | n/a | >>> ExtendedContext.remainder(Decimal(22), 6) |

5351 | n/a | Decimal('4') |

5352 | n/a | >>> ExtendedContext.remainder(22, Decimal(6)) |

5353 | n/a | Decimal('4') |

5354 | n/a | """ |

5355 | n/a | a = _convert_other(a, raiseit=True) |

5356 | n/a | r = a.__mod__(b, context=self) |

5357 | n/a | if r is NotImplemented: |

5358 | n/a | raise TypeError("Unable to convert %s to Decimal" % b) |

5359 | n/a | else: |

5360 | n/a | return r |

5361 | n/a | |

5362 | n/a | def remainder_near(self, a, b): |

5363 | n/a | """Returns to be "a - b * n", where n is the integer nearest the exact |

5364 | n/a | value of "x / b" (if two integers are equally near then the even one |

5365 | n/a | is chosen). If the result is equal to 0 then its sign will be the |

5366 | n/a | sign of a. |

5367 | n/a | |

5368 | n/a | This operation will fail under the same conditions as integer division |

5369 | n/a | (that is, if integer division on the same two operands would fail, the |

5370 | n/a | remainder cannot be calculated). |

5371 | n/a | |

5372 | n/a | >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) |

5373 | n/a | Decimal('-0.9') |

5374 | n/a | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) |

5375 | n/a | Decimal('-2') |

5376 | n/a | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) |

5377 | n/a | Decimal('1') |

5378 | n/a | >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) |

5379 | n/a | Decimal('-1') |

5380 | n/a | >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) |

5381 | n/a | Decimal('0.2') |

5382 | n/a | >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) |

5383 | n/a | Decimal('0.1') |

5384 | n/a | >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) |

5385 | n/a | Decimal('-0.3') |

5386 | n/a | >>> ExtendedContext.remainder_near(3, 11) |

5387 | n/a | Decimal('3') |

5388 | n/a | >>> ExtendedContext.remainder_near(Decimal(3), 11) |

5389 | n/a | Decimal('3') |

5390 | n/a | >>> ExtendedContext.remainder_near(3, Decimal(11)) |

5391 | n/a | Decimal('3') |

5392 | n/a | """ |

5393 | n/a | a = _convert_other(a, raiseit=True) |

5394 | n/a | return a.remainder_near(b, context=self) |

5395 | n/a | |

5396 | n/a | def rotate(self, a, b): |

5397 | n/a | """Returns a rotated copy of a, b times. |

5398 | n/a | |

5399 | n/a | The coefficient of the result is a rotated copy of the digits in |

5400 | n/a | the coefficient of the first operand. The number of places of |

5401 | n/a | rotation is taken from the absolute value of the second operand, |

5402 | n/a | with the rotation being to the left if the second operand is |

5403 | n/a | positive or to the right otherwise. |

5404 | n/a | |

5405 | n/a | >>> ExtendedContext.rotate(Decimal('34'), Decimal('8')) |

5406 | n/a | Decimal('400000003') |

5407 | n/a | >>> ExtendedContext.rotate(Decimal('12'), Decimal('9')) |

5408 | n/a | Decimal('12') |

5409 | n/a | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2')) |

5410 | n/a | Decimal('891234567') |

5411 | n/a | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0')) |

5412 | n/a | Decimal('123456789') |

5413 | n/a | >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2')) |

5414 | n/a | Decimal('345678912') |

5415 | n/a | >>> ExtendedContext.rotate(1333333, 1) |

5416 | n/a | Decimal('13333330') |

5417 | n/a | >>> ExtendedContext.rotate(Decimal(1333333), 1) |

5418 | n/a | Decimal('13333330') |

5419 | n/a | >>> ExtendedContext.rotate(1333333, Decimal(1)) |

5420 | n/a | Decimal('13333330') |

5421 | n/a | """ |

5422 | n/a | a = _convert_other(a, raiseit=True) |

5423 | n/a | return a.rotate(b, context=self) |

5424 | n/a | |

5425 | n/a | def same_quantum(self, a, b): |

5426 | n/a | """Returns True if the two operands have the same exponent. |

5427 | n/a | |

5428 | n/a | The result is never affected by either the sign or the coefficient of |

5429 | n/a | either operand. |

5430 | n/a | |

5431 | n/a | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) |

5432 | n/a | False |

5433 | n/a | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) |

5434 | n/a | True |

5435 | n/a | >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) |

5436 | n/a | False |

5437 | n/a | >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) |

5438 | n/a | True |

5439 | n/a | >>> ExtendedContext.same_quantum(10000, -1) |

5440 | n/a | True |

5441 | n/a | >>> ExtendedContext.same_quantum(Decimal(10000), -1) |

5442 | n/a | True |

5443 | n/a | >>> ExtendedContext.same_quantum(10000, Decimal(-1)) |

5444 | n/a | True |

5445 | n/a | """ |

5446 | n/a | a = _convert_other(a, raiseit=True) |

5447 | n/a | return a.same_quantum(b) |

5448 | n/a | |

5449 | n/a | def scaleb (self, a, b): |

5450 | n/a | """Returns the first operand after adding the second value its exp. |

5451 | n/a | |

5452 | n/a | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) |

5453 | n/a | Decimal('0.0750') |

5454 | n/a | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) |

5455 | n/a | Decimal('7.50') |

5456 | n/a | >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) |

5457 | n/a | Decimal('7.50E+3') |

5458 | n/a | >>> ExtendedContext.scaleb(1, 4) |

5459 | n/a | Decimal('1E+4') |

5460 | n/a | >>> ExtendedContext.scaleb(Decimal(1), 4) |

5461 | n/a | Decimal('1E+4') |

5462 | n/a | >>> ExtendedContext.scaleb(1, Decimal(4)) |

5463 | n/a | Decimal('1E+4') |

5464 | n/a | """ |

5465 | n/a | a = _convert_other(a, raiseit=True) |

5466 | n/a | return a.scaleb(b, context=self) |

5467 | n/a | |

5468 | n/a | def shift(self, a, b): |

5469 | n/a | """Returns a shifted copy of a, b times. |

5470 | n/a | |

5471 | n/a | The coefficient of the result is a shifted copy of the digits |

5472 | n/a | in the coefficient of the first operand. The number of places |

5473 | n/a | to shift is taken from the absolute value of the second operand, |

5474 | n/a | with the shift being to the left if the second operand is |

5475 | n/a | positive or to the right otherwise. Digits shifted into the |

5476 | n/a | coefficient are zeros. |

5477 | n/a | |

5478 | n/a | >>> ExtendedContext.shift(Decimal('34'), Decimal('8')) |

5479 | n/a | Decimal('400000000') |

5480 | n/a | >>> ExtendedContext.shift(Decimal('12'), Decimal('9')) |

5481 | n/a | Decimal('0') |

5482 | n/a | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2')) |

5483 | n/a | Decimal('1234567') |

5484 | n/a | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0')) |

5485 | n/a | Decimal('123456789') |

5486 | n/a | >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2')) |

5487 | n/a | Decimal('345678900') |

5488 | n/a | >>> ExtendedContext.shift(88888888, 2) |

5489 | n/a | Decimal('888888800') |

5490 | n/a | >>> ExtendedContext.shift(Decimal(88888888), 2) |

5491 | n/a | Decimal('888888800') |

5492 | n/a | >>> ExtendedContext.shift(88888888, Decimal(2)) |

5493 | n/a | Decimal('888888800') |

5494 | n/a | """ |

5495 | n/a | a = _convert_other(a, raiseit=True) |

5496 | n/a | return a.shift(b, context=self) |

5497 | n/a | |

5498 | n/a | def sqrt(self, a): |

5499 | n/a | """Square root of a non-negative number to context precision. |

5500 | n/a | |

5501 | n/a | If the result must be inexact, it is rounded using the round-half-even |

5502 | n/a | algorithm. |

5503 | n/a | |

5504 | n/a | >>> ExtendedContext.sqrt(Decimal('0')) |

5505 | n/a | Decimal('0') |

5506 | n/a | >>> ExtendedContext.sqrt(Decimal('-0')) |

5507 | n/a | Decimal('-0') |

5508 | n/a | >>> ExtendedContext.sqrt(Decimal('0.39')) |

5509 | n/a | Decimal('0.624499800') |

5510 | n/a | >>> ExtendedContext.sqrt(Decimal('100')) |

5511 | n/a | Decimal('10') |

5512 | n/a | >>> ExtendedContext.sqrt(Decimal('1')) |

5513 | n/a | Decimal('1') |

5514 | n/a | >>> ExtendedContext.sqrt(Decimal('1.0')) |

5515 | n/a | Decimal('1.0') |

5516 | n/a | >>> ExtendedContext.sqrt(Decimal('1.00')) |

5517 | n/a | Decimal('1.0') |

5518 | n/a | >>> ExtendedContext.sqrt(Decimal('7')) |

5519 | n/a | Decimal('2.64575131') |

5520 | n/a | >>> ExtendedContext.sqrt(Decimal('10')) |

5521 | n/a | Decimal('3.16227766') |

5522 | n/a | >>> ExtendedContext.sqrt(2) |

5523 | n/a | Decimal('1.41421356') |

5524 | n/a | >>> ExtendedContext.prec |

5525 | n/a | 9 |

5526 | n/a | """ |

5527 | n/a | a = _convert_other(a, raiseit=True) |

5528 | n/a | return a.sqrt(context=self) |

5529 | n/a | |

5530 | n/a | def subtract(self, a, b): |

5531 | n/a | """Return the difference between the two operands. |

5532 | n/a | |

5533 | n/a | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) |

5534 | n/a | Decimal('0.23') |

5535 | n/a | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) |

5536 | n/a | Decimal('0.00') |

5537 | n/a | >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) |

5538 | n/a | Decimal('-0.77') |

5539 | n/a | >>> ExtendedContext.subtract(8, 5) |

5540 | n/a | Decimal('3') |

5541 | n/a | >>> ExtendedContext.subtract(Decimal(8), 5) |

5542 | n/a | Decimal('3') |

5543 | n/a | >>> ExtendedContext.subtract(8, Decimal(5)) |

5544 | n/a | Decimal('3') |

5545 | n/a | """ |

5546 | n/a | a = _convert_other(a, raiseit=True) |

5547 | n/a | r = a.__sub__(b, context=self) |

5548 | n/a | if r is NotImplemented: |

5549 | n/a | raise TypeError("Unable to convert %s to Decimal" % b) |

5550 | n/a | else: |

5551 | n/a | return r |

5552 | n/a | |

5553 | n/a | def to_eng_string(self, a): |

5554 | n/a | """Convert to a string, using engineering notation if an exponent is needed. |

5555 | n/a | |

5556 | n/a | Engineering notation has an exponent which is a multiple of 3. This |

5557 | n/a | can leave up to 3 digits to the left of the decimal place and may |

5558 | n/a | require the addition of either one or two trailing zeros. |

5559 | n/a | |

5560 | n/a | The operation is not affected by the context. |

5561 | n/a | |

5562 | n/a | >>> ExtendedContext.to_eng_string(Decimal('123E+1')) |

5563 | n/a | '1.23E+3' |

5564 | n/a | >>> ExtendedContext.to_eng_string(Decimal('123E+3')) |

5565 | n/a | '123E+3' |

5566 | n/a | >>> ExtendedContext.to_eng_string(Decimal('123E-10')) |

5567 | n/a | '12.3E-9' |

5568 | n/a | >>> ExtendedContext.to_eng_string(Decimal('-123E-12')) |

5569 | n/a | '-123E-12' |

5570 | n/a | >>> ExtendedContext.to_eng_string(Decimal('7E-7')) |

5571 | n/a | '700E-9' |

5572 | n/a | >>> ExtendedContext.to_eng_string(Decimal('7E+1')) |

5573 | n/a | '70' |

5574 | n/a | >>> ExtendedContext.to_eng_string(Decimal('0E+1')) |

5575 | n/a | '0.00E+3' |

5576 | n/a | |

5577 | n/a | """ |

5578 | n/a | a = _convert_other(a, raiseit=True) |

5579 | n/a | return a.to_eng_string(context=self) |

5580 | n/a | |

5581 | n/a | def to_sci_string(self, a): |

5582 | n/a | """Converts a number to a string, using scientific notation. |

5583 | n/a | |

5584 | n/a | The operation is not affected by the context. |

5585 | n/a | """ |

5586 | n/a | a = _convert_other(a, raiseit=True) |

5587 | n/a | return a.__str__(context=self) |

5588 | n/a | |

5589 | n/a | def to_integral_exact(self, a): |

5590 | n/a | """Rounds to an integer. |

5591 | n/a | |

5592 | n/a | When the operand has a negative exponent, the result is the same |

5593 | n/a | as using the quantize() operation using the given operand as the |

5594 | n/a | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |

5595 | n/a | of the operand as the precision setting; Inexact and Rounded flags |

5596 | n/a | are allowed in this operation. The rounding mode is taken from the |

5597 | n/a | context. |

5598 | n/a | |

5599 | n/a | >>> ExtendedContext.to_integral_exact(Decimal('2.1')) |

5600 | n/a | Decimal('2') |

5601 | n/a | >>> ExtendedContext.to_integral_exact(Decimal('100')) |

5602 | n/a | Decimal('100') |

5603 | n/a | >>> ExtendedContext.to_integral_exact(Decimal('100.0')) |

5604 | n/a | Decimal('100') |

5605 | n/a | >>> ExtendedContext.to_integral_exact(Decimal('101.5')) |

5606 | n/a | Decimal('102') |

5607 | n/a | >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) |

5608 | n/a | Decimal('-102') |

5609 | n/a | >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) |

5610 | n/a | Decimal('1.0E+6') |

5611 | n/a | >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) |

5612 | n/a | Decimal('7.89E+77') |

5613 | n/a | >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) |

5614 | n/a | Decimal('-Infinity') |

5615 | n/a | """ |

5616 | n/a | a = _convert_other(a, raiseit=True) |

5617 | n/a | return a.to_integral_exact(context=self) |

5618 | n/a | |

5619 | n/a | def to_integral_value(self, a): |

5620 | n/a | """Rounds to an integer. |

5621 | n/a | |

5622 | n/a | When the operand has a negative exponent, the result is the same |

5623 | n/a | as using the quantize() operation using the given operand as the |

5624 | n/a | left-hand-operand, 1E+0 as the right-hand-operand, and the precision |

5625 | n/a | of the operand as the precision setting, except that no flags will |

5626 | n/a | be set. The rounding mode is taken from the context. |

5627 | n/a | |

5628 | n/a | >>> ExtendedContext.to_integral_value(Decimal('2.1')) |

5629 | n/a | Decimal('2') |

5630 | n/a | >>> ExtendedContext.to_integral_value(Decimal('100')) |

5631 | n/a | Decimal('100') |

5632 | n/a | >>> ExtendedContext.to_integral_value(Decimal('100.0')) |

5633 | n/a | Decimal('100') |

5634 | n/a | >>> ExtendedContext.to_integral_value(Decimal('101.5')) |

5635 | n/a | Decimal('102') |

5636 | n/a | >>> ExtendedContext.to_integral_value(Decimal('-101.5')) |

5637 | n/a | Decimal('-102') |

5638 | n/a | >>> ExtendedContext.to_integral_value(Decimal('10E+5')) |

5639 | n/a | Decimal('1.0E+6') |

5640 | n/a | >>> ExtendedContext.to_integral_value(Decimal('7.89E+77')) |

5641 | n/a | Decimal('7.89E+77') |

5642 | n/a | >>> ExtendedContext.to_integral_value(Decimal('-Inf')) |

5643 | n/a | Decimal('-Infinity') |

5644 | n/a | """ |

5645 | n/a | a = _convert_other(a, raiseit=True) |

5646 | n/a | return a.to_integral_value(context=self) |

5647 | n/a | |

5648 | n/a | # the method name changed, but we provide also the old one, for compatibility |

5649 | n/a | to_integral = to_integral_value |

5650 | n/a | |

5651 | n/a | class _WorkRep(object): |

5652 | n/a | __slots__ = ('sign','int','exp') |

5653 | n/a | # sign: 0 or 1 |

5654 | n/a | # int: int |

5655 | n/a | # exp: None, int, or string |

5656 | n/a | |

5657 | n/a | def __init__(self, value=None): |

5658 | n/a | if value is None: |

5659 | n/a | self.sign = None |

5660 | n/a | self.int = 0 |

5661 | n/a | self.exp = None |

5662 | n/a | elif isinstance(value, Decimal): |

5663 | n/a | self.sign = value._sign |

5664 | n/a | self.int = int(value._int) |

5665 | n/a | self.exp = value._exp |

5666 | n/a | else: |

5667 | n/a | # assert isinstance(value, tuple) |

5668 | n/a | self.sign = value[0] |

5669 | n/a | self.int = value[1] |

5670 | n/a | self.exp = value[2] |

5671 | n/a | |

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

5673 | n/a | return "(%r, %r, %r)" % (self.sign, self.int, self.exp) |

5674 | n/a | |

5675 | n/a | __str__ = __repr__ |

5676 | n/a | |

5677 | n/a | |

5678 | n/a | |

5679 | n/a | def _normalize(op1, op2, prec = 0): |

5680 | n/a | """Normalizes op1, op2 to have the same exp and length of coefficient. |

5681 | n/a | |

5682 | n/a | Done during addition. |

5683 | n/a | """ |

5684 | n/a | if op1.exp < op2.exp: |

5685 | n/a | tmp = op2 |

5686 | n/a | other = op1 |

5687 | n/a | else: |

5688 | n/a | tmp = op1 |

5689 | n/a | other = op2 |

5690 | n/a | |

5691 | n/a | # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1). |

5692 | n/a | # Then adding 10**exp to tmp has the same effect (after rounding) |

5693 | n/a | # as adding any positive quantity smaller than 10**exp; similarly |

5694 | n/a | # for subtraction. So if other is smaller than 10**exp we replace |

5695 | n/a | # it with 10**exp. This avoids tmp.exp - other.exp getting too large. |

5696 | n/a | tmp_len = len(str(tmp.int)) |

5697 | n/a | other_len = len(str(other.int)) |

5698 | n/a | exp = tmp.exp + min(-1, tmp_len - prec - 2) |

5699 | n/a | if other_len + other.exp - 1 < exp: |

5700 | n/a | other.int = 1 |

5701 | n/a | other.exp = exp |

5702 | n/a | |

5703 | n/a | tmp.int *= 10 ** (tmp.exp - other.exp) |

5704 | n/a | tmp.exp = other.exp |

5705 | n/a | return op1, op2 |

5706 | n/a | |

5707 | n/a | ##### Integer arithmetic functions used by ln, log10, exp and __pow__ ##### |

5708 | n/a | |

5709 | n/a | _nbits = int.bit_length |

5710 | n/a | |

5711 | n/a | def _decimal_lshift_exact(n, e): |

5712 | n/a | """ Given integers n and e, return n * 10**e if it's an integer, else None. |

5713 | n/a | |

5714 | n/a | The computation is designed to avoid computing large powers of 10 |

5715 | n/a | unnecessarily. |

5716 | n/a | |

5717 | n/a | >>> _decimal_lshift_exact(3, 4) |

5718 | n/a | 30000 |

5719 | n/a | >>> _decimal_lshift_exact(300, -999999999) # returns None |

5720 | n/a | |

5721 | n/a | """ |

5722 | n/a | if n == 0: |

5723 | n/a | return 0 |

5724 | n/a | elif e >= 0: |

5725 | n/a | return n * 10**e |

5726 | n/a | else: |

5727 | n/a | # val_n = largest power of 10 dividing n. |

5728 | n/a | str_n = str(abs(n)) |

5729 | n/a | val_n = len(str_n) - len(str_n.rstrip('0')) |

5730 | n/a | return None if val_n < -e else n // 10**-e |

5731 | n/a | |

5732 | n/a | def _sqrt_nearest(n, a): |

5733 | n/a | """Closest integer to the square root of the positive integer n. a is |

5734 | n/a | an initial approximation to the square root. Any positive integer |

5735 | n/a | will do for a, but the closer a is to the square root of n the |

5736 | n/a | faster convergence will be. |

5737 | n/a | |

5738 | n/a | """ |

5739 | n/a | if n <= 0 or a <= 0: |

5740 | n/a | raise ValueError("Both arguments to _sqrt_nearest should be positive.") |

5741 | n/a | |

5742 | n/a | b=0 |

5743 | n/a | while a != b: |

5744 | n/a | b, a = a, a--n//a>>1 |

5745 | n/a | return a |

5746 | n/a | |

5747 | n/a | def _rshift_nearest(x, shift): |

5748 | n/a | """Given an integer x and a nonnegative integer shift, return closest |

5749 | n/a | integer to x / 2**shift; use round-to-even in case of a tie. |

5750 | n/a | |

5751 | n/a | """ |

5752 | n/a | b, q = 1 << shift, x >> shift |

5753 | n/a | return q + (2*(x & (b-1)) + (q&1) > b) |

5754 | n/a | |

5755 | n/a | def _div_nearest(a, b): |

5756 | n/a | """Closest integer to a/b, a and b positive integers; rounds to even |

5757 | n/a | in the case of a tie. |

5758 | n/a | |

5759 | n/a | """ |

5760 | n/a | q, r = divmod(a, b) |

5761 | n/a | return q + (2*r + (q&1) > b) |

5762 | n/a | |

5763 | n/a | def _ilog(x, M, L = 8): |

5764 | n/a | """Integer approximation to M*log(x/M), with absolute error boundable |

5765 | n/a | in terms only of x/M. |

5766 | n/a | |

5767 | n/a | Given positive integers x and M, return an integer approximation to |

5768 | n/a | M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference |

5769 | n/a | between the approximation and the exact result is at most 22. For |

5770 | n/a | L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In |

5771 | n/a | both cases these are upper bounds on the error; it will usually be |

5772 | n/a | much smaller.""" |

5773 | n/a | |

5774 | n/a | # The basic algorithm is the following: let log1p be the function |

5775 | n/a | # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use |

5776 | n/a | # the reduction |

5777 | n/a | # |

5778 | n/a | # log1p(y) = 2*log1p(y/(1+sqrt(1+y))) |

5779 | n/a | # |

5780 | n/a | # repeatedly until the argument to log1p is small (< 2**-L in |

5781 | n/a | # absolute value). For small y we can use the Taylor series |

5782 | n/a | # expansion |

5783 | n/a | # |

5784 | n/a | # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T |

5785 | n/a | # |

5786 | n/a | # truncating at T such that y**T is small enough. The whole |

5787 | n/a | # computation is carried out in a form of fixed-point arithmetic, |

5788 | n/a | # with a real number z being represented by an integer |

5789 | n/a | # approximation to z*M. To avoid loss of precision, the y below |

5790 | n/a | # is actually an integer approximation to 2**R*y*M, where R is the |

5791 | n/a | # number of reductions performed so far. |

5792 | n/a | |

5793 | n/a | y = x-M |

5794 | n/a | # argument reduction; R = number of reductions performed |

5795 | n/a | R = 0 |

5796 | n/a | while (R <= L and abs(y) << L-R >= M or |

5797 | n/a | R > L and abs(y) >> R-L >= M): |

5798 | n/a | y = _div_nearest((M*y) << 1, |

5799 | n/a | M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M)) |

5800 | n/a | R += 1 |

5801 | n/a | |

5802 | n/a | # Taylor series with T terms |

5803 | n/a | T = -int(-10*len(str(M))//(3*L)) |

5804 | n/a | yshift = _rshift_nearest(y, R) |

5805 | n/a | w = _div_nearest(M, T) |

5806 | n/a | for k in range(T-1, 0, -1): |

5807 | n/a | w = _div_nearest(M, k) - _div_nearest(yshift*w, M) |

5808 | n/a | |

5809 | n/a | return _div_nearest(w*y, M) |

5810 | n/a | |

5811 | n/a | def _dlog10(c, e, p): |

5812 | n/a | """Given integers c, e and p with c > 0, p >= 0, compute an integer |

5813 | n/a | approximation to 10**p * log10(c*10**e), with an absolute error of |

5814 | n/a | at most 1. Assumes that c*10**e is not exactly 1.""" |

5815 | n/a | |

5816 | n/a | # increase precision by 2; compensate for this by dividing |

5817 | n/a | # final result by 100 |

5818 | n/a | p += 2 |

5819 | n/a | |

5820 | n/a | # write c*10**e as d*10**f with either: |

5821 | n/a | # f >= 0 and 1 <= d <= 10, or |

5822 | n/a | # f <= 0 and 0.1 <= d <= 1. |

5823 | n/a | # Thus for c*10**e close to 1, f = 0 |

5824 | n/a | l = len(str(c)) |

5825 | n/a | f = e+l - (e+l >= 1) |

5826 | n/a | |

5827 | n/a | if p > 0: |

5828 | n/a | M = 10**p |

5829 | n/a | k = e+p-f |

5830 | n/a | if k >= 0: |

5831 | n/a | c *= 10**k |

5832 | n/a | else: |

5833 | n/a | c = _div_nearest(c, 10**-k) |

5834 | n/a | |

5835 | n/a | log_d = _ilog(c, M) # error < 5 + 22 = 27 |

5836 | n/a | log_10 = _log10_digits(p) # error < 1 |

5837 | n/a | log_d = _div_nearest(log_d*M, log_10) |

5838 | n/a | log_tenpower = f*M # exact |

5839 | n/a | else: |

5840 | n/a | log_d = 0 # error < 2.31 |

5841 | n/a | log_tenpower = _div_nearest(f, 10**-p) # error < 0.5 |

5842 | n/a | |

5843 | n/a | return _div_nearest(log_tenpower+log_d, 100) |

5844 | n/a | |

5845 | n/a | def _dlog(c, e, p): |

5846 | n/a | """Given integers c, e and p with c > 0, compute an integer |

5847 | n/a | approximation to 10**p * log(c*10**e), with an absolute error of |

5848 | n/a | at most 1. Assumes that c*10**e is not exactly 1.""" |

5849 | n/a | |

5850 | n/a | # Increase precision by 2. The precision increase is compensated |

5851 | n/a | # for at the end with a division by 100. |

5852 | n/a | p += 2 |

5853 | n/a | |

5854 | n/a | # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10, |

5855 | n/a | # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e) |

5856 | n/a | # as 10**p * log(d) + 10**p*f * log(10). |

5857 | n/a | l = len(str(c)) |

5858 | n/a | f = e+l - (e+l >= 1) |

5859 | n/a | |

5860 | n/a | # compute approximation to 10**p*log(d), with error < 27 |

5861 | n/a | if p > 0: |

5862 | n/a | k = e+p-f |

5863 | n/a | if k >= 0: |

5864 | n/a | c *= 10**k |

5865 | n/a | else: |

5866 | n/a | c = _div_nearest(c, 10**-k) # error of <= 0.5 in c |

5867 | n/a | |

5868 | n/a | # _ilog magnifies existing error in c by a factor of at most 10 |

5869 | n/a | log_d = _ilog(c, 10**p) # error < 5 + 22 = 27 |

5870 | n/a | else: |

5871 | n/a | # p <= 0: just approximate the whole thing by 0; error < 2.31 |

5872 | n/a | log_d = 0 |

5873 | n/a | |

5874 | n/a | # compute approximation to f*10**p*log(10), with error < 11. |

5875 | n/a | if f: |

5876 | n/a | extra = len(str(abs(f)))-1 |

5877 | n/a | if p + extra >= 0: |

5878 | n/a | # error in f * _log10_digits(p+extra) < |f| * 1 = |f| |

5879 | n/a | # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11 |

5880 | n/a | f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra) |

5881 | n/a | else: |

5882 | n/a | f_log_ten = 0 |

5883 | n/a | else: |

5884 | n/a | f_log_ten = 0 |

5885 | n/a | |

5886 | n/a | # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1 |

5887 | n/a | return _div_nearest(f_log_ten + log_d, 100) |

5888 | n/a | |

5889 | n/a | class _Log10Memoize(object): |

5890 | n/a | """Class to compute, store, and allow retrieval of, digits of the |

5891 | n/a | constant log(10) = 2.302585.... This constant is needed by |

5892 | n/a | Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__.""" |

5893 | n/a | def __init__(self): |

5894 | n/a | self.digits = "23025850929940456840179914546843642076011014886" |

5895 | n/a | |

5896 | n/a | def getdigits(self, p): |

5897 | n/a | """Given an integer p >= 0, return floor(10**p)*log(10). |

5898 | n/a | |

5899 | n/a | For example, self.getdigits(3) returns 2302. |

5900 | n/a | """ |

5901 | n/a | # digits are stored as a string, for quick conversion to |

5902 | n/a | # integer in the case that we've already computed enough |

5903 | n/a | # digits; the stored digits should always be correct |

5904 | n/a | # (truncated, not rounded to nearest). |

5905 | n/a | if p < 0: |

5906 | n/a | raise ValueError("p should be nonnegative") |

5907 | n/a | |

5908 | n/a | if p >= len(self.digits): |

5909 | n/a | # compute p+3, p+6, p+9, ... digits; continue until at |

5910 | n/a | # least one of the extra digits is nonzero |

5911 | n/a | extra = 3 |

5912 | n/a | while True: |

5913 | n/a | # compute p+extra digits, correct to within 1ulp |

5914 | n/a | M = 10**(p+extra+2) |

5915 | n/a | digits = str(_div_nearest(_ilog(10*M, M), 100)) |

5916 | n/a | if digits[-extra:] != '0'*extra: |

5917 | n/a | break |

5918 | n/a | extra += 3 |

5919 | n/a | # keep all reliable digits so far; remove trailing zeros |

5920 | n/a | # and next nonzero digit |

5921 | n/a | self.digits = digits.rstrip('0')[:-1] |

5922 | n/a | return int(self.digits[:p+1]) |

5923 | n/a | |

5924 | n/a | _log10_digits = _Log10Memoize().getdigits |

5925 | n/a | |

5926 | n/a | def _iexp(x, M, L=8): |

5927 | n/a | """Given integers x and M, M > 0, such that x/M is small in absolute |

5928 | n/a | value, compute an integer approximation to M*exp(x/M). For 0 <= |

5929 | n/a | x/M <= 2.4, the absolute error in the result is bounded by 60 (and |

5930 | n/a | is usually much smaller).""" |

5931 | n/a | |

5932 | n/a | # Algorithm: to compute exp(z) for a real number z, first divide z |

5933 | n/a | # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then |

5934 | n/a | # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor |

5935 | n/a | # series |

5936 | n/a | # |

5937 | n/a | # expm1(x) = x + x**2/2! + x**3/3! + ... |

5938 | n/a | # |

5939 | n/a | # Now use the identity |

5940 | n/a | # |

5941 | n/a | # expm1(2x) = expm1(x)*(expm1(x)+2) |

5942 | n/a | # |

5943 | n/a | # R times to compute the sequence expm1(z/2**R), |

5944 | n/a | # expm1(z/2**(R-1)), ... , exp(z/2), exp(z). |

5945 | n/a | |

5946 | n/a | # Find R such that x/2**R/M <= 2**-L |

5947 | n/a | R = _nbits((x<<L)//M) |

5948 | n/a | |

5949 | n/a | # Taylor series. (2**L)**T > M |

5950 | n/a | T = -int(-10*len(str(M))//(3*L)) |

5951 | n/a | y = _div_nearest(x, T) |

5952 | n/a | Mshift = M<<R |

5953 | n/a | for i in range(T-1, 0, -1): |

5954 | n/a | y = _div_nearest(x*(Mshift + y), Mshift * i) |

5955 | n/a | |

5956 | n/a | # Expansion |

5957 | n/a | for k in range(R-1, -1, -1): |

5958 | n/a | Mshift = M<<(k+2) |

5959 | n/a | y = _div_nearest(y*(y+Mshift), Mshift) |

5960 | n/a | |

5961 | n/a | return M+y |

5962 | n/a | |

5963 | n/a | def _dexp(c, e, p): |

5964 | n/a | """Compute an approximation to exp(c*10**e), with p decimal places of |

5965 | n/a | precision. |

5966 | n/a | |

5967 | n/a | Returns integers d, f such that: |

5968 | n/a | |

5969 | n/a | 10**(p-1) <= d <= 10**p, and |

5970 | n/a | (d-1)*10**f < exp(c*10**e) < (d+1)*10**f |

5971 | n/a | |

5972 | n/a | In other words, d*10**f is an approximation to exp(c*10**e) with p |

5973 | n/a | digits of precision, and with an error in d of at most 1. This is |

5974 | n/a | almost, but not quite, the same as the error being < 1ulp: when d |

5975 | n/a | = 10**(p-1) the error could be up to 10 ulp.""" |

5976 | n/a | |

5977 | n/a | # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision |

5978 | n/a | p += 2 |

5979 | n/a | |

5980 | n/a | # compute log(10) with extra precision = adjusted exponent of c*10**e |

5981 | n/a | extra = max(0, e + len(str(c)) - 1) |

5982 | n/a | q = p + extra |

5983 | n/a | |

5984 | n/a | # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q), |

5985 | n/a | # rounding down |

5986 | n/a | shift = e+q |

5987 | n/a | if shift >= 0: |

5988 | n/a | cshift = c*10**shift |

5989 | n/a | else: |

5990 | n/a | cshift = c//10**-shift |

5991 | n/a | quot, rem = divmod(cshift, _log10_digits(q)) |

5992 | n/a | |

5993 | n/a | # reduce remainder back to original precision |

5994 | n/a | rem = _div_nearest(rem, 10**extra) |

5995 | n/a | |

5996 | n/a | # error in result of _iexp < 120; error after division < 0.62 |

5997 | n/a | return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3 |

5998 | n/a | |

5999 | n/a | def _dpower(xc, xe, yc, ye, p): |

6000 | n/a | """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and |

6001 | n/a | y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: |

6002 | n/a | |

6003 | n/a | 10**(p-1) <= c <= 10**p, and |

6004 | n/a | (c-1)*10**e < x**y < (c+1)*10**e |

6005 | n/a | |

6006 | n/a | in other words, c*10**e is an approximation to x**y with p digits |

6007 | n/a | of precision, and with an error in c of at most 1. (This is |

6008 | n/a | almost, but not quite, the same as the error being < 1ulp: when c |

6009 | n/a | == 10**(p-1) we can only guarantee error < 10ulp.) |

6010 | n/a | |

6011 | n/a | We assume that: x is positive and not equal to 1, and y is nonzero. |

6012 | n/a | """ |

6013 | n/a | |

6014 | n/a | # Find b such that 10**(b-1) <= |y| <= 10**b |

6015 | n/a | b = len(str(abs(yc))) + ye |

6016 | n/a | |

6017 | n/a | # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point |

6018 | n/a | lxc = _dlog(xc, xe, p+b+1) |

6019 | n/a | |

6020 | n/a | # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) |

6021 | n/a | shift = ye-b |

6022 | n/a | if shift >= 0: |

6023 | n/a | pc = lxc*yc*10**shift |

6024 | n/a | else: |

6025 | n/a | pc = _div_nearest(lxc*yc, 10**-shift) |

6026 | n/a | |

6027 | n/a | if pc == 0: |

6028 | n/a | # we prefer a result that isn't exactly 1; this makes it |

6029 | n/a | # easier to compute a correctly rounded result in __pow__ |

6030 | n/a | if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: |

6031 | n/a | coeff, exp = 10**(p-1)+1, 1-p |

6032 | n/a | else: |

6033 | n/a | coeff, exp = 10**p-1, -p |

6034 | n/a | else: |

6035 | n/a | coeff, exp = _dexp(pc, -(p+1), p+1) |

6036 | n/a | coeff = _div_nearest(coeff, 10) |

6037 | n/a | exp += 1 |

6038 | n/a | |

6039 | n/a | return coeff, exp |

6040 | n/a | |

6041 | n/a | def _log10_lb(c, correction = { |

6042 | n/a | '1': 100, '2': 70, '3': 53, '4': 40, '5': 31, |

6043 | n/a | '6': 23, '7': 16, '8': 10, '9': 5}): |

6044 | n/a | """Compute a lower bound for 100*log10(c) for a positive integer c.""" |

6045 | n/a | if c <= 0: |

6046 | n/a | raise ValueError("The argument to _log10_lb should be nonnegative.") |

6047 | n/a | str_c = str(c) |

6048 | n/a | return 100*len(str_c) - correction[str_c[0]] |

6049 | n/a | |

6050 | n/a | ##### Helper Functions #################################################### |

6051 | n/a | |

6052 | n/a | def _convert_other(other, raiseit=False, allow_float=False): |

6053 | n/a | """Convert other to Decimal. |

6054 | n/a | |

6055 | n/a | Verifies that it's ok to use in an implicit construction. |

6056 | n/a | If allow_float is true, allow conversion from float; this |

6057 | n/a | is used in the comparison methods (__eq__ and friends). |

6058 | n/a | |

6059 | n/a | """ |

6060 | n/a | if isinstance(other, Decimal): |

6061 | n/a | return other |

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

6063 | n/a | return Decimal(other) |

6064 | n/a | if allow_float and isinstance(other, float): |

6065 | n/a | return Decimal.from_float(other) |

6066 | n/a | |

6067 | n/a | if raiseit: |

6068 | n/a | raise TypeError("Unable to convert %s to Decimal" % other) |

6069 | n/a | return NotImplemented |

6070 | n/a | |

6071 | n/a | def _convert_for_comparison(self, other, equality_op=False): |

6072 | n/a | """Given a Decimal instance self and a Python object other, return |

6073 | n/a | a pair (s, o) of Decimal instances such that "s op o" is |

6074 | n/a | equivalent to "self op other" for any of the 6 comparison |

6075 | n/a | operators "op". |

6076 | n/a | |

6077 | n/a | """ |

6078 | n/a | if isinstance(other, Decimal): |

6079 | n/a | return self, other |

6080 | n/a | |

6081 | n/a | # Comparison with a Rational instance (also includes integers): |

6082 | n/a | # self op n/d <=> self*d op n (for n and d integers, d positive). |

6083 | n/a | # A NaN or infinity can be left unchanged without affecting the |

6084 | n/a | # comparison result. |

6085 | n/a | if isinstance(other, _numbers.Rational): |

6086 | n/a | if not self._is_special: |

6087 | n/a | self = _dec_from_triple(self._sign, |

6088 | n/a | str(int(self._int) * other.denominator), |

6089 | n/a | self._exp) |

6090 | n/a | return self, Decimal(other.numerator) |

6091 | n/a | |

6092 | n/a | # Comparisons with float and complex types. == and != comparisons |

6093 | n/a | # with complex numbers should succeed, returning either True or False |

6094 | n/a | # as appropriate. Other comparisons return NotImplemented. |

6095 | n/a | if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0: |

6096 | n/a | other = other.real |

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

6098 | n/a | context = getcontext() |

6099 | n/a | if equality_op: |

6100 | n/a | context.flags[FloatOperation] = 1 |

6101 | n/a | else: |

6102 | n/a | context._raise_error(FloatOperation, |

6103 | n/a | "strict semantics for mixing floats and Decimals are enabled") |

6104 | n/a | return self, Decimal.from_float(other) |

6105 | n/a | return NotImplemented, NotImplemented |

6106 | n/a | |

6107 | n/a | |

6108 | n/a | ##### Setup Specific Contexts ############################################ |

6109 | n/a | |

6110 | n/a | # The default context prototype used by Context() |

6111 | n/a | # Is mutable, so that new contexts can have different default values |

6112 | n/a | |

6113 | n/a | DefaultContext = Context( |

6114 | n/a | prec=28, rounding=ROUND_HALF_EVEN, |

6115 | n/a | traps=[DivisionByZero, Overflow, InvalidOperation], |

6116 | n/a | flags=[], |

6117 | n/a | Emax=999999, |

6118 | n/a | Emin=-999999, |

6119 | n/a | capitals=1, |

6120 | n/a | clamp=0 |

6121 | n/a | ) |

6122 | n/a | |

6123 | n/a | # Pre-made alternate contexts offered by the specification |

6124 | n/a | # Don't change these; the user should be able to select these |

6125 | n/a | # contexts and be able to reproduce results from other implementations |

6126 | n/a | # of the spec. |

6127 | n/a | |

6128 | n/a | BasicContext = Context( |

6129 | n/a | prec=9, rounding=ROUND_HALF_UP, |

6130 | n/a | traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], |

6131 | n/a | flags=[], |

6132 | n/a | ) |

6133 | n/a | |

6134 | n/a | ExtendedContext = Context( |

6135 | n/a | prec=9, rounding=ROUND_HALF_EVEN, |

6136 | n/a | traps=[], |

6137 | n/a | flags=[], |

6138 | n/a | ) |

6139 | n/a | |

6140 | n/a | |

6141 | n/a | ##### crud for parsing strings ############################################# |

6142 | n/a | # |

6143 | n/a | # Regular expression used for parsing numeric strings. Additional |

6144 | n/a | # comments: |

6145 | n/a | # |

6146 | n/a | # 1. Uncomment the two '\s*' lines to allow leading and/or trailing |

6147 | n/a | # whitespace. But note that the specification disallows whitespace in |

6148 | n/a | # a numeric string. |

6149 | n/a | # |

6150 | n/a | # 2. For finite numbers (not infinities and NaNs) the body of the |

6151 | n/a | # number between the optional sign and the optional exponent must have |

6152 | n/a | # at least one decimal digit, possibly after the decimal point. The |

6153 | n/a | # lookahead expression '(?=\d|\.\d)' checks this. |

6154 | n/a | |

6155 | n/a | import re |

6156 | n/a | _parser = re.compile(r""" # A numeric string consists of: |

6157 | n/a | # \s* |

6158 | n/a | (?P<sign>[-+])? # an optional sign, followed by either... |

6159 | n/a | ( |

6160 | n/a | (?=\d|\.\d) # ...a number (with at least one digit) |

6161 | n/a | (?P<int>\d*) # having a (possibly empty) integer part |

6162 | n/a | (\.(?P<frac>\d*))? # followed by an optional fractional part |

6163 | n/a | (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or... |

6164 | n/a | | |

6165 | n/a | Inf(inity)? # ...an infinity, or... |

6166 | n/a | | |

6167 | n/a | (?P<signal>s)? # ...an (optionally signaling) |

6168 | n/a | NaN # NaN |

6169 | n/a | (?P<diag>\d*) # with (possibly empty) diagnostic info. |

6170 | n/a | ) |

6171 | n/a | # \s* |

6172 | n/a | \Z |

6173 | n/a | """, re.VERBOSE | re.IGNORECASE).match |

6174 | n/a | |

6175 | n/a | _all_zeros = re.compile('0*$').match |

6176 | n/a | _exact_half = re.compile('50*$').match |

6177 | n/a | |

6178 | n/a | ##### PEP3101 support functions ############################################## |

6179 | n/a | # The functions in this section have little to do with the Decimal |

6180 | n/a | # class, and could potentially be reused or adapted for other pure |

6181 | n/a | # Python numeric classes that want to implement __format__ |

6182 | n/a | # |

6183 | n/a | # A format specifier for Decimal looks like: |

6184 | n/a | # |

6185 | n/a | # [[fill]align][sign][#][0][minimumwidth][,][.precision][type] |

6186 | n/a | |

6187 | n/a | _parse_format_specifier_regex = re.compile(r"""\A |

6188 | n/a | (?: |

6189 | n/a | (?P<fill>.)? |

6190 | n/a | (?P<align>[<>=^]) |

6191 | n/a | )? |

6192 | n/a | (?P<sign>[-+ ])? |

6193 | n/a | (?P<alt>\#)? |

6194 | n/a | (?P<zeropad>0)? |

6195 | n/a | (?P<minimumwidth>(?!0)\d+)? |

6196 | n/a | (?P<thousands_sep>,)? |

6197 | n/a | (?:\.(?P<precision>0|(?!0)\d+))? |

6198 | n/a | (?P<type>[eEfFgGn%])? |

6199 | n/a | \Z |

6200 | n/a | """, re.VERBOSE|re.DOTALL) |

6201 | n/a | |

6202 | n/a | del re |

6203 | n/a | |

6204 | n/a | # The locale module is only needed for the 'n' format specifier. The |

6205 | n/a | # rest of the PEP 3101 code functions quite happily without it, so we |

6206 | n/a | # don't care too much if locale isn't present. |

6207 | n/a | try: |

6208 | n/a | import locale as _locale |

6209 | n/a | except ImportError: |

6210 | n/a | pass |

6211 | n/a | |

6212 | n/a | def _parse_format_specifier(format_spec, _localeconv=None): |

6213 | n/a | """Parse and validate a format specifier. |

6214 | n/a | |

6215 | n/a | Turns a standard numeric format specifier into a dict, with the |

6216 | n/a | following entries: |

6217 | n/a | |

6218 | n/a | fill: fill character to pad field to minimum width |

6219 | n/a | align: alignment type, either '<', '>', '=' or '^' |

6220 | n/a | sign: either '+', '-' or ' ' |

6221 | n/a | minimumwidth: nonnegative integer giving minimum width |

6222 | n/a | zeropad: boolean, indicating whether to pad with zeros |

6223 | n/a | thousands_sep: string to use as thousands separator, or '' |

6224 | n/a | grouping: grouping for thousands separators, in format |

6225 | n/a | used by localeconv |

6226 | n/a | decimal_point: string to use for decimal point |

6227 | n/a | precision: nonnegative integer giving precision, or None |

6228 | n/a | type: one of the characters 'eEfFgG%', or None |

6229 | n/a | |

6230 | n/a | """ |

6231 | n/a | m = _parse_format_specifier_regex.match(format_spec) |

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

6233 | n/a | raise ValueError("Invalid format specifier: " + format_spec) |

6234 | n/a | |

6235 | n/a | # get the dictionary |

6236 | n/a | format_dict = m.groupdict() |

6237 | n/a | |

6238 | n/a | # zeropad; defaults for fill and alignment. If zero padding |

6239 | n/a | # is requested, the fill and align fields should be absent. |

6240 | n/a | fill = format_dict['fill'] |

6241 | n/a | align = format_dict['align'] |

6242 | n/a | format_dict['zeropad'] = (format_dict['zeropad'] is not None) |

6243 | n/a | if format_dict['zeropad']: |

6244 | n/a | if fill is not None: |

6245 | n/a | raise ValueError("Fill character conflicts with '0'" |

6246 | n/a | " in format specifier: " + format_spec) |

6247 | n/a | if align is not None: |

6248 | n/a | raise ValueError("Alignment conflicts with '0' in " |

6249 | n/a | "format specifier: " + format_spec) |

6250 | n/a | format_dict['fill'] = fill or ' ' |

6251 | n/a | # PEP 3101 originally specified that the default alignment should |

6252 | n/a | # be left; it was later agreed that right-aligned makes more sense |

6253 | n/a | # for numeric types. See http://bugs.python.org/issue6857. |

6254 | n/a | format_dict['align'] = align or '>' |

6255 | n/a | |

6256 | n/a | # default sign handling: '-' for negative, '' for positive |

6257 | n/a | if format_dict['sign'] is None: |

6258 | n/a | format_dict['sign'] = '-' |

6259 | n/a | |

6260 | n/a | # minimumwidth defaults to 0; precision remains None if not given |

6261 | n/a | format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0') |

6262 | n/a | if format_dict['precision'] is not None: |

6263 | n/a | format_dict['precision'] = int(format_dict['precision']) |

6264 | n/a | |

6265 | n/a | # if format type is 'g' or 'G' then a precision of 0 makes little |

6266 | n/a | # sense; convert it to 1. Same if format type is unspecified. |

6267 | n/a | if format_dict['precision'] == 0: |

6268 | n/a | if format_dict['type'] is None or format_dict['type'] in 'gGn': |

6269 | n/a | format_dict['precision'] = 1 |

6270 | n/a | |

6271 | n/a | # determine thousands separator, grouping, and decimal separator, and |

6272 | n/a | # add appropriate entries to format_dict |

6273 | n/a | if format_dict['type'] == 'n': |

6274 | n/a | # apart from separators, 'n' behaves just like 'g' |

6275 | n/a | format_dict['type'] = 'g' |

6276 | n/a | if _localeconv is None: |

6277 | n/a | _localeconv = _locale.localeconv() |

6278 | n/a | if format_dict['thousands_sep'] is not None: |

6279 | n/a | raise ValueError("Explicit thousands separator conflicts with " |

6280 | n/a | "'n' type in format specifier: " + format_spec) |

6281 | n/a | format_dict['thousands_sep'] = _localeconv['thousands_sep'] |

6282 | n/a | format_dict['grouping'] = _localeconv['grouping'] |

6283 | n/a | format_dict['decimal_point'] = _localeconv['decimal_point'] |

6284 | n/a | else: |

6285 | n/a | if format_dict['thousands_sep'] is None: |

6286 | n/a | format_dict['thousands_sep'] = '' |

6287 | n/a | format_dict['grouping'] = [3, 0] |

6288 | n/a | format_dict['decimal_point'] = '.' |

6289 | n/a | |

6290 | n/a | return format_dict |

6291 | n/a | |

6292 | n/a | def _format_align(sign, body, spec): |

6293 | n/a | """Given an unpadded, non-aligned numeric string 'body' and sign |

6294 | n/a | string 'sign', add padding and alignment conforming to the given |

6295 | n/a | format specifier dictionary 'spec' (as produced by |

6296 | n/a | parse_format_specifier). |

6297 | n/a | |

6298 | n/a | """ |

6299 | n/a | # how much extra space do we have to play with? |

6300 | n/a | minimumwidth = spec['minimumwidth'] |

6301 | n/a | fill = spec['fill'] |

6302 | n/a | padding = fill*(minimumwidth - len(sign) - len(body)) |

6303 | n/a | |

6304 | n/a | align = spec['align'] |

6305 | n/a | if align == '<': |

6306 | n/a | result = sign + body + padding |

6307 | n/a | elif align == '>': |

6308 | n/a | result = padding + sign + body |

6309 | n/a | elif align == '=': |

6310 | n/a | result = sign + padding + body |

6311 | n/a | elif align == '^': |

6312 | n/a | half = len(padding)//2 |

6313 | n/a | result = padding[:half] + sign + body + padding[half:] |

6314 | n/a | else: |

6315 | n/a | raise ValueError('Unrecognised alignment field') |

6316 | n/a | |

6317 | n/a | return result |

6318 | n/a | |

6319 | n/a | def _group_lengths(grouping): |

6320 | n/a | """Convert a localeconv-style grouping into a (possibly infinite) |

6321 | n/a | iterable of integers representing group lengths. |

6322 | n/a | |

6323 | n/a | """ |

6324 | n/a | # The result from localeconv()['grouping'], and the input to this |

6325 | n/a | # function, should be a list of integers in one of the |

6326 | n/a | # following three forms: |

6327 | n/a | # |

6328 | n/a | # (1) an empty list, or |

6329 | n/a | # (2) nonempty list of positive integers + [0] |

6330 | n/a | # (3) list of positive integers + [locale.CHAR_MAX], or |

6331 | n/a | |

6332 | n/a | from itertools import chain, repeat |

6333 | n/a | if not grouping: |

6334 | n/a | return [] |

6335 | n/a | elif grouping[-1] == 0 and len(grouping) >= 2: |

6336 | n/a | return chain(grouping[:-1], repeat(grouping[-2])) |

6337 | n/a | elif grouping[-1] == _locale.CHAR_MAX: |

6338 | n/a | return grouping[:-1] |

6339 | n/a | else: |

6340 | n/a | raise ValueError('unrecognised format for grouping') |

6341 | n/a | |

6342 | n/a | def _insert_thousands_sep(digits, spec, min_width=1): |

6343 | n/a | """Insert thousands separators into a digit string. |

6344 | n/a | |

6345 | n/a | spec is a dictionary whose keys should include 'thousands_sep' and |

6346 | n/a | 'grouping'; typically it's the result of parsing the format |

6347 | n/a | specifier using _parse_format_specifier. |

6348 | n/a | |

6349 | n/a | The min_width keyword argument gives the minimum length of the |

6350 | n/a | result, which will be padded on the left with zeros if necessary. |

6351 | n/a | |

6352 | n/a | If necessary, the zero padding adds an extra '0' on the left to |

6353 | n/a | avoid a leading thousands separator. For example, inserting |

6354 | n/a | commas every three digits in '123456', with min_width=8, gives |

6355 | n/a | '0,123,456', even though that has length 9. |

6356 | n/a | |

6357 | n/a | """ |

6358 | n/a | |

6359 | n/a | sep = spec['thousands_sep'] |

6360 | n/a | grouping = spec['grouping'] |

6361 | n/a | |

6362 | n/a | groups = [] |

6363 | n/a | for l in _group_lengths(grouping): |

6364 | n/a | if l <= 0: |

6365 | n/a | raise ValueError("group length should be positive") |

6366 | n/a | # max(..., 1) forces at least 1 digit to the left of a separator |

6367 | n/a | l = min(max(len(digits), min_width, 1), l) |

6368 | n/a | groups.append('0'*(l - len(digits)) + digits[-l:]) |

6369 | n/a | digits = digits[:-l] |

6370 | n/a | min_width -= l |

6371 | n/a | if not digits and min_width <= 0: |

6372 | n/a | break |

6373 | n/a | min_width -= len(sep) |

6374 | n/a | else: |

6375 | n/a | l = max(len(digits), min_width, 1) |

6376 | n/a | groups.append('0'*(l - len(digits)) + digits[-l:]) |

6377 | n/a | return sep.join(reversed(groups)) |

6378 | n/a | |

6379 | n/a | def _format_sign(is_negative, spec): |

6380 | n/a | """Determine sign character.""" |

6381 | n/a | |

6382 | n/a | if is_negative: |

6383 | n/a | return '-' |

6384 | n/a | elif spec['sign'] in ' +': |

6385 | n/a | return spec['sign'] |

6386 | n/a | else: |

6387 | n/a | return '' |

6388 | n/a | |

6389 | n/a | def _format_number(is_negative, intpart, fracpart, exp, spec): |

6390 | n/a | """Format a number, given the following data: |

6391 | n/a | |

6392 | n/a | is_negative: true if the number is negative, else false |

6393 | n/a | intpart: string of digits that must appear before the decimal point |

6394 | n/a | fracpart: string of digits that must come after the point |

6395 | n/a | exp: exponent, as an integer |

6396 | n/a | spec: dictionary resulting from parsing the format specifier |

6397 | n/a | |

6398 | n/a | This function uses the information in spec to: |

6399 | n/a | insert separators (decimal separator and thousands separators) |

6400 | n/a | format the sign |

6401 | n/a | format the exponent |

6402 | n/a | add trailing '%' for the '%' type |

6403 | n/a | zero-pad if necessary |

6404 | n/a | fill and align if necessary |

6405 | n/a | """ |

6406 | n/a | |

6407 | n/a | sign = _format_sign(is_negative, spec) |

6408 | n/a | |

6409 | n/a | if fracpart or spec['alt']: |

6410 | n/a | fracpart = spec['decimal_point'] + fracpart |

6411 | n/a | |

6412 | n/a | if exp != 0 or spec['type'] in 'eE': |

6413 | n/a | echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']] |

6414 | n/a | fracpart += "{0}{1:+}".format(echar, exp) |

6415 | n/a | if spec['type'] == '%': |

6416 | n/a | fracpart += '%' |

6417 | n/a | |

6418 | n/a | if spec['zeropad']: |

6419 | n/a | min_width = spec['minimumwidth'] - len(fracpart) - len(sign) |

6420 | n/a | else: |

6421 | n/a | min_width = 0 |

6422 | n/a | intpart = _insert_thousands_sep(intpart, spec, min_width) |

6423 | n/a | |

6424 | n/a | return _format_align(sign, intpart+fracpart, spec) |

6425 | n/a | |

6426 | n/a | |

6427 | n/a | ##### Useful Constants (internal use only) ################################ |

6428 | n/a | |

6429 | n/a | # Reusable defaults |

6430 | n/a | _Infinity = Decimal('Inf') |

6431 | n/a | _NegativeInfinity = Decimal('-Inf') |

6432 | n/a | _NaN = Decimal('NaN') |

6433 | n/a | _Zero = Decimal(0) |

6434 | n/a | _One = Decimal(1) |

6435 | n/a | _NegativeOne = Decimal(-1) |

6436 | n/a | |

6437 | n/a | # _SignedInfinity[sign] is infinity w/ that sign |

6438 | n/a | _SignedInfinity = (_Infinity, _NegativeInfinity) |

6439 | n/a | |

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

6441 | n/a | # on the reduction of x modulo _PyHASH_MODULUS |

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

6443 | n/a | # hash values to use for positive and negative infinities, and nans |

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

6445 | n/a | _PyHASH_NAN = sys.hash_info.nan |

6446 | n/a | |

6447 | n/a | # _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS |

6448 | n/a | _PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS) |

6449 | n/a | del sys |