Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

100 digit floating point python

I have a large decimal number, such as the square root of 2, and I want to view the first 100 decimal digits. However, float does not support this capability: 1.4142135623730951454746218587388284504413604736328125000000000000000000000000000000000000000000000000

What is the best way to do this? I do not want to import anything, preferably

like image 444
Noooo Avatar asked Dec 15 '15 01:12

Noooo


People also ask

How many digits can a Python float hold?

Python float values are represented as 64-bit double-precision values. The maximum value any floating-point number can be is approx 1.8 x 10308.

Is Python float 32 or 64?

Python's floating-point numbers are usually 64-bit floating-point numbers, nearly equivalent to np.float64 . In some unusual situations it may be useful to use floating-point numbers with more precision.


1 Answers

If your requirement for precision is 100 decimal digits, I think you have to use decimal.Decimal.

The float in Python is not designed for this kind of precise calculation.

Using decimal.Decimal is almost as simple as float, you can do +, -, *, / and some other commonly used calculations directly between any decimal.Decimal without any consideration.

Also, decimal.Decimal supports setting up the precision directly you want:

>>> from decimal import getcontext, Decimal
>>> getcontext().prec = 6
>>> Decimal(1) / Decimal(7)
Decimal('0.142857')
>>> getcontext().prec = 28
>>> Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')

You can find more detail in this Python2 API or Python3 API

like image 140
resec Avatar answered Sep 24 '22 23:09

resec