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

五迷三道 提交于 2019-11-27 13:17:16

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))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!