Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between printing `float32` directly and using `format()` function in Python

Consider following floating point number:

number = 2.695274829864502

When I print it I get:

print(number) # 2.695274829864502

When I convert it to float32 I get truncated number:

import numpy as np
number32 = np.float32(number)
print(number32) # 2.6952748

Same is when I call __repr__() or __str__():

print(number32.__str__()) # 2.6952748
print(number32.__repr__()) # 2.6952748

However, when use I format() function I get the original number:

print("{}".format(number32)) # 2.695274829864502

It happens in both Python3.5 and in Python3.6. Python2.7 has similar behavior except that for a longer version of the number it truncates 4 trailing digits.

What is the explanation for this?

like image 622
Vlad Avatar asked Sep 17 '26 11:09

Vlad


1 Answers

This is probably just a difference in display, meaning, the class float32 probably specifies a different number of digits to display after the decimal point.

Some code to highlight the differences:

n1 = 2.695274829864502
print()
print('n1 type     ', type(n1))
print('n1          ', n1)
print('n1.__str__  ', n1.__str__())
print('n1.__repr__ ', n1.__repr__())
print('n1 {}       ', '{}'.format(n1))
print('n1 {:.30f}  ', '{:.30f}'.format(n1))

n2 = np.float32(n1)
print()
print('n2 type     ', type(n2))
print('n2          ', n2)
print('n2.__str__  ', n2.__str__())
print('n2.__repr__ ', n2.__repr__())
print('n2 {}       ', '{}'.format(n2))
print('n2 {:.30f}  ', '{:.30f}'.format(n2))

n3 = np.float64(n1)
print()
print('n3 type     ', type(n3))
print('n3          ', n3)
print('n3.__str__  ', n3.__str__())
print('n3.__repr__ ', n3.__repr__())
print('n3 {}       ', '{}'.format(n3))
print('n3 {:.30f}  ', '{:.30f}'.format(n3))

The results (using Python 3.6):

n1 type      <class 'float'>
n1           2.695274829864502
n1.__str__   2.695274829864502
n1.__repr__  2.695274829864502
n1 {}        2.695274829864502
n1 {:.30f}   2.695274829864501953125000000000

n2 type      <class 'numpy.float32'>
n2           2.6952748
n2.__str__   2.6952748
n2.__repr__  2.6952748
n2 {}        2.695274829864502
n2 {:.30f}   2.695274829864501953125000000000

n3 type      <class 'numpy.float64'>
n3           2.695274829864502
n3.__str__   2.695274829864502
n3.__repr__  2.695274829864502
n3 {}        2.695274829864502
n3 {:.30f}   2.695274829864501953125000000000

As you can see, internally all digits are still there, they just are not shown when using some display methods.

I don't think that this is a bug or that it would affect the calculation results with these variables; this seems to be normal (and expected) behaviour.

like image 181
Ralf Avatar answered Sep 19 '26 04:09

Ralf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!