Case 1:
for num in [.1, .2, .3, .4, .5, .6, .7, .8, .9,]:
print(format(num, ".50f"))
0.10000000000000000555111512312578270211815834045410
0.20000000000000001110223024625156540423631668090820
0.29999999999999998889776975374843459576368331909180
0.40000000000000002220446049250313080847263336181641
0.50000000000000000000000000000000000000000000000000
0.59999999999999997779553950749686919152736663818359
0.69999999999999995559107901499373838305473327636719
0.80000000000000004440892098500626161694526672363281
0.90000000000000002220446049250313080847263336181641
Imprecision, as expected (except .5
).
Case 2:
for num in [1., 2., 3., 4., 5., 6., 7., 8., 9.]:
print(format(num, ".50f"))
1.00000000000000000000000000000000000000000000000000
2.00000000000000000000000000000000000000000000000000
3.00000000000000000000000000000000000000000000000000
4.00000000000000000000000000000000000000000000000000
5.00000000000000000000000000000000000000000000000000
6.00000000000000000000000000000000000000000000000000
7.00000000000000000000000000000000000000000000000000
8.00000000000000000000000000000000000000000000000000
9.00000000000000000000000000000000000000000000000000
Perfect precision - ???
As is known, there's no such thing as a perfect float integer in computing: all floats are represented in terms of a binary base, with increasing precision depending on bitsize (float32
, float64
, etc). So what's the deal with Case 2 above? The zeros persist even for ".1000f"
, basically implying infinite precision. Further, 0.5
is also somehow represented perfectly.
If format
cannot force Python to print the "true" value of a float, then what can?
Attempted alternatives:
format(round(num, 50), ".50f")
format(numpy.float128(num), ".50f")
format(round(numpy.float128(num), 50), ".50f")
format("%.50f" % num)
"{:.50f}".format(num))
f"{num:.50f}"
ACCEPTED ANSWER: clarifies false premise assumed in the question; the answer to the actual question is within the question itself - use format
to show true numeric value.