0

If i print a list of float contained in a list there is no problem, but if I print only one single float of this list of list, it not print all the digits!

listafeaturevector = [

[0.26912666717306399, 0.012738398606387012, 0.011347858467581035, 0.1896938013442868, 2.444553429782046]
,
[0.36793086934925351, 0.034364344308391102, 0.019054536791551006, 0.0076875387476751395, 3.03091214703604]
,
[0.36793086934925351, 0.034364344308391102, 0.019054536791551006, 0.0076875387476751395, 3.03091214703604]
,
[0.30406240228443038, 0.047100329090555518, 0.0049653458889261448, 0.0004618404341300081, 5.987025009738751]

]

for i in range (0,len(listafeaturevector)):
    a = listafeaturevector[i]
    print(a[0])
    print(",")
    print(a)
    for j in range (0, len(a)  ):
        print(a[j])

this prints all digits:

print(a) 

this prints partial digits:

print(a[0]) 
dmg
  • 7,438
  • 2
  • 24
  • 33
postgres
  • 2,242
  • 5
  • 34
  • 50

4 Answers4

4

This is because, the floats are converted to string by calling the __str__ method. This will truncate the digits. If you wan't the exact representation, you should rather call __repr__ method through the repr built-in to get the entire float representation

Another important factor here is that the precision of your floats are higher than the IEEE 64 bit representable formats. So there will be some truncation

example

>>> print 0.26912666717306399
0.269126667173
>>> print repr(0.26912666717306399)
0.269126667173064
>>> print("%.16f" % 0.26912666717306399)
0.2691266671730640
>>> 
Abhijit
  • 62,056
  • 18
  • 131
  • 204
2

You can specify the number of digits you want after the decimal point:

print("%.15f" % a[j])
unwind
  • 391,730
  • 64
  • 469
  • 606
1

The reason for that is that when you print a list it calls the __str__ method of the list, which in turn calls the __repr__ method of each of it's items. Quoting the docs

object.__repr__(self) Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).

So __repr__ should try to be as close to the object as possible. So:

>>> repr(0.012738398606387012)
'0.012738398606387012'
>>> str(0.012738398606387012)
'0.0127383986064'

list being the model citizen that he is tries to make all of it's items seem meaningful. Which is why your numbers don't get truncated.

Using this simple test class we can observe the same behaviour:

class B():
    def __str__(self): return 'STR CALLED'
    def __repr__(self): return 'REPR CALLED'


>>> print(B())
STR CALLED
>>> print([B()])
[REPR CALLED]
dmg
  • 7,438
  • 2
  • 24
  • 33
0

Try using string formatting:

print(".%15f" % a[0])
sfendell
  • 5,415
  • 8
  • 25
  • 26