Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More Digits in Irrational Numbers

>>> str(1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702)
'1.41421356237'

Is there a way I can make str() record more digits of the number into the string? I don't understand why it truncates by default.

like image 511
Sylvester V Lowell Avatar asked Feb 16 '23 07:02

Sylvester V Lowell


2 Answers

Python's floating point numbers use double precision only, which is 64 bits. They simply cannot represent (significantly) more digits than you're seeing.

If you need more, have a look at the built-in decimal module, or the mpmath package.

like image 159
Thomas Avatar answered Feb 27 '23 16:02

Thomas


Try this:

>>> from decimal import *
>>> Decimal('1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702')
Decimal('1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702')

The float literal is truncated by default to fit in the space made available for it (i.e. it's not because of str):

>>> 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702
1.4142135623730951

If you need more decimal places use decimal instead.

like image 23
arshajii Avatar answered Feb 27 '23 17:02

arshajii