Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make numbers more precise in Python? [duplicate]

I'm just learning the basics of Python at the moment and I thought that, as a learning exercise, I'd try writing something that would approximate the number "e". Anyway, it always gives the answer to 11 decimal places and I want it to give something more like 1000 decimal places. How do I do I do this?

like image 384
M Smith Avatar asked Sep 03 '26 14:09

M Smith


2 Answers

Are you sure you need to make them "more precise"? Or do you just need to see more digits than Python shows by default?

>>> import math
>>> math.pi
3.141592653589793
>>>
>>> '{0:0.2f}'.format(math.pi)
'3.14'
>>>
>>> '{0:0.30f}'.format(math.pi)
'3.141592653589793115997963468544'
>>>
>>> '{0:0.60f}'.format(math.pi)
'3.141592653589793115997963468544185161590576171875000000000000'

However, note that

Floating point numbers are usually implemented using double in C; information about the precision and internal representation of floating point numbers for the machine on which your program is running is available in sys.float_info

I assure you that pi doesn't go to zero after 48 digits :-)

like image 190
Jonathon Reinhart Avatar answered Sep 05 '26 03:09

Jonathon Reinhart


Almost all machines today use IEEE-754 floating point arithmetic, and almost all platforms map Python floats to IEEE-754 “double precision”.

A IEEE-754 double has 64 bits (8 bytes), with the 52 bits of the fraction significand appearing in the memory format, the total precision is approximately 16 decimal digits.

So to represent a float number have a higher precise than that, you should use Decimal.

import decimal
decimal.getcontext().prec = 100
like image 26
Leonardo.Z Avatar answered Sep 05 '26 04:09

Leonardo.Z