1

I've tried various techniques but I can't figure out how to print out 100 decimal places of sqrt(2). decimal.Decimal seems to be counteracted by the calculation itself. Any ideas?

import decimal
import math

decimal.getcontext().dps = 100   #arbitrary

print(decimal.Decimal(math.sqrt(2)))
mistermarko
  • 305
  • 1
  • 3
  • 20
  • 1
    Will `sqrt(2)` actually calculate the square root of 2 correct to 100 decimal places, or will you run into floating-point accuracy limitations? – Hammerite Jun 23 '14 at 09:38

1 Answers1

4

math.sqrt(2) returns a float value, which doesn't support the precision you are asking for. Use Decimal.sqrt() instead:

>>> from decimal import Decimal, localcontext
>>> with localcontext() as ctx:
...     ctx.prec = 100
...     Decimal(2).sqrt()
... 
Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343