Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i show an irrational number to 100 decimal places in python?

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?

like image 811
clayton33 Avatar asked Jan 19 '11 08:01

clayton33


People also ask

How do you round to the 100th place in Python?

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.

How do you find the irrational number of a decimal?

When an irrational number is changed into a decimal, the resulting number is a nonterminating, nonrecurring decimal. Therefore, √2 = 1.4142.... It is nonterminating.

How many decimal places is Python accurate to?

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.


4 Answers

decimal module comes in handy.

>>> from decimal import *
>>> getcontext().prec = 100
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573')
like image 68
Senthil Kumaran Avatar answered Oct 14 '22 16:10

Senthil Kumaran


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.

like image 40
TryPyPy Avatar answered Oct 14 '22 16:10

TryPyPy


You can use gmpy2.

import gmpy2
ctx = gmpy2.get_context()
ctx.precision = 300
print(gmpy2.sqrt(2))
like image 20
Christian Berendt Avatar answered Oct 14 '22 16:10

Christian Berendt


You can use sympy and evalf()

from sympy import sqrt
print(sqrt(2).evalf(101))
like image 34
maro Avatar answered Oct 14 '22 18:10

maro