Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def d(n, precision=50):
- """
- Given x is either an int or a float with 12 or fewer digits,
- return decimal.Decimal(str(x)).
- This function appears in a simpler form in the 2nd ed. of
- _Python In a Nutshell_, p.373
- #>>> from decimal import Decimal as D
- #>>> decimal.getcontext().prec = 50
- #>>> D('234')**D('.555555555555555')
- #Decimal('20.712428960882622698237158800584555118350558990840')
- >>> d(234)**d(.555555555555555)
- Decimal('20.712428960882622698237158800584555118350558990840')
- >>> d(234, 25)**d(.555555555555555)
- Decimal('20.712428960882622698237158800584555118350558990840')
- >>> d(234)**d(.555555555555555, 25)
- Decimal('20.71242896088262269823716')
- >>> d(234)**d(.5555555555555557)
- float beginning 0.555 has too many digits.
- Maximum to maintain accuracy is 15
- (<http://www.wolframalpha.com/input/?i=234**.555555555555555>
- gives 20.71242896088262269823715880058455511835055899083967...)
- """
- import decimal
- from decimal import getcontext
- getcontext().prec = precision
- import sys
- from decimal import Decimal as D
- if isinstance(n, float):
- with decimal.localcontext() as ctx:
- ctx.prec = 15
- if D(str(n)) != +D(str(n)):
- print('float beginning', str(n)[:5], 'has too many digits.')
- print('Maximum to maintain accuracy is 15 digits')
- sys.exit()
- elif isinstance(n, int):
- pass
- else:
- raise TypeError("WTF you didn't pass me an int or a float")
- return D(str(n))
Advertisement
Add Comment
Please, Sign In to add comment