4
>>> 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.

BNL
  • 7,085
  • 4
  • 27
  • 32
Sylvester V Lowell
  • 1,243
  • 1
  • 12
  • 13

4 Answers4

5

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.

Thomas
  • 174,939
  • 50
  • 355
  • 478
2

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.

arshajii
  • 127,459
  • 24
  • 238
  • 287
1

The Python compiler is truncating; your float literal has more precision than can be represented in a C double. Express the number as a string in the first place if you need more precision.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

That's because it's converting to a float. It's not the conversion to the string that's causing it. You should use decimal.Decimal for representing such high precision numbers.

Sid
  • 7,511
  • 2
  • 28
  • 41