16

I am trying to find the square root of 2 to 100 decimal places, but it only shows to like 10 by default, how can I change this?

clayton33
  • 4,176
  • 10
  • 45
  • 64

4 Answers4

35

decimal module comes in handy.

>>> from decimal import *
>>> getcontext().prec = 100
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573')
Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131
7

You can use the decimal module for arbitrary precision numbers:

import decimal

d2 = decimal.Decimal(2)

# Add a context with an arbitrary precision of 100
dot100 = decimal.Context(prec=100)

print d2.sqrt(dot100)

If you need the same kind of ability coupled to speed, there are some other options: [gmpy], 2, cdecimal.

TryPyPy
  • 6,214
  • 5
  • 35
  • 63
2

You can use gmpy2.

import gmpy2
ctx = gmpy2.get_context()
ctx.precision = 300
print(gmpy2.sqrt(2))
Christian Berendt
  • 3,416
  • 2
  • 13
  • 22
  • For me was the best solution. By using the library `decimal` also you can get a similar solution but if you want to work with the number (more than just show up in a screen), for me was easier this one. Thanks. – Nicolás Rodríguez Aug 26 '21 at 13:01
1

You can use sympy and evalf()

from sympy import sqrt
print(sqrt(2).evalf(101))
maro
  • 473
  • 4
  • 11
  • 30