3

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?

M Smith
  • 430
  • 1
  • 7
  • 19

3 Answers3

4

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 :-)

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
1

If you want it to be a number, with a precision of a thousand digits, the short answer is you can't..

A workaround is, you can use the decimal module. Here is an example:

import decimal
a = decimal.Decimal('2387324895172987120570935712093570921579217509185712093')

In this case, however, a is not a number anymore. It's just an instance of the decimal.Decimal class. Well, you can still do some math operations with it.

aIKid
  • 26,968
  • 4
  • 39
  • 65
  • *Computers* can store anything you can encode in as few bits as the computer can store (which is, as you might recall, in the order of billions to trillions these days). What you're calling a "number" is just one specific encoding (IEEE 754 double-precision floats). And in Python, floats are just an instance of the `float` class. A `Decimal` object is as much of a number as a `float` object. Neither is in any way special as far as computer science is concerned. –  Oct 23 '13 at 07:28
1

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
Leonardo.Z
  • 9,425
  • 3
  • 35
  • 38