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?
Use the round() function to round a number to the nearest 100, e.g. result = round(num, -2) . When the round() function is called with a second argument of -2 , it rounds to the closest multiple of one hundred.
When an irrational number is changed into a decimal, the resulting number is a nonterminating, nonrecurring decimal. Therefore, √2 = 1.4142.... It is nonterminating.
Python Decimal default precision The Decimal has a default precision of 28 places, while the float has 18 places. The example compars the precision of two floating point types in Python.
decimal module comes in handy.
>>> from decimal import *
>>> getcontext().prec = 100
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573')
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.
You can use gmpy2.
import gmpy2
ctx = gmpy2.get_context()
ctx.precision = 300
print(gmpy2.sqrt(2))
You can use sympy and evalf()
from sympy import sqrt
print(sqrt(2).evalf(101))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With