pyzuki

def d(n, precision=50)

Mar 8th, 2011
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. def d(n, precision=50):
  2.     """
  3.    Given x is either an int or a float with 12 or fewer digits,
  4.    return decimal.Decimal(str(x)).
  5.    
  6.    This function appears in a simpler form in the 2nd ed. of
  7.    _Python In a Nutshell_, p.373
  8.    
  9.    #>>> from decimal import Decimal as D
  10.    #>>> decimal.getcontext().prec = 50
  11.    #>>> D('234')**D('.555555555555555')
  12.    #Decimal('20.712428960882622698237158800584555118350558990840')
  13.    >>> d(234)**d(.555555555555555)
  14.    Decimal('20.712428960882622698237158800584555118350558990840')
  15.    >>> d(234, 25)**d(.555555555555555)
  16.    Decimal('20.712428960882622698237158800584555118350558990840')
  17.    >>> d(234)**d(.555555555555555, 25)
  18.    Decimal('20.71242896088262269823716')
  19.    >>> d(234)**d(.5555555555555557)
  20.    float beginning 0.555 has too many digits.
  21.    Maximum to maintain accuracy is 15
  22.    (<http://www.wolframalpha.com/input/?i=234**.555555555555555>
  23.    gives 20.71242896088262269823715880058455511835055899083967...)
  24.    """
  25.     import decimal
  26.     from decimal import getcontext
  27.     getcontext().prec = precision
  28.     import sys
  29.     from decimal import Decimal as D
  30.    
  31.     if isinstance(n, float):
  32.         with decimal.localcontext() as ctx:
  33.             ctx.prec = 15
  34.             if D(str(n)) != +D(str(n)):
  35.                 print('float beginning', str(n)[:5], 'has too many digits.')
  36.                 print('Maximum to maintain accuracy is 15 digits')
  37.                 sys.exit()
  38.        
  39.     elif isinstance(n, int):
  40.         pass
  41.     else:
  42.         raise TypeError("WTF you didn't pass me an int or a float")
  43.     return D(str(n))
Advertisement
Add Comment
Please, Sign In to add comment