Print a float value
Hailiang Shen
Hello all, could anyone help me understand printing float values? E.g.
print (7.0/3) will output 2.33333333333 print (7/3.0, 7.0/3) will output (2.3333333333333335, 2.3333333333333335)
I am not sure why the outputs are slightly different.
Regards,
Hailiang
|
|
Stéphane Lozier
In the first case you're printing the float, in the second case you're printing a tuple of floats. In both cases the `__str__` function is called, however in the case of the tuple, `__str__` and `__repr__` are the same so it's like calling `__repr__` of each of its items. >>> class test(object): ... def __str__(self): return "__str__" ... def __repr__(self): return "__repr__" ... >>> print(test()) __str__ >>> print(test(), test()) (__repr__, __repr__) Hope this makes sense. Stéphane
On Sat, Mar 21, 2020 at 7:08 PM Hailiang Shen <hailiang@...> wrote:
|
|
Hailiang Shen
Thanks Stéphane. This clarified why the results were different. I was also wondering why the 2nd print outputs 2.3333333333333335, where the last digit is not 3 but 5.
From: users@ironpython.groups.io <users@ironpython.groups.io>
On Behalf Of Stéphane Lozier
Sent: March 22, 2020 10:45 AM To: users@ironpython.groups.io Subject: Re: [ironpython] Print a float value
In the first case you're printing the float, in the second case you're printing a tuple of floats. In both cases the `__str__` function is called, however in the case of the tuple, `__str__` and `__repr__` are the same so it's like calling `__repr__` of each of its items.
>>> class test(object):
Hope this makes sense.
Stéphane
On Sat, Mar 21, 2020 at 7:08 PM Hailiang Shen <hailiang@...> wrote:
|
|
Stéphane Lozier
The rational number 7/3 cannot be expressed exactly using a float. The result of 7.0/3 is actually 2.333333333333333481363069950020872056484222412109375. So when you round to 17 significant digits you end up with the trailing 35. For more information on floating point numbers I suggest looking at https://en.wikipedia.org/wiki/Double-precision_floating-point_format Stéphane
On Sun, Mar 22, 2020 at 11:01 AM Hailiang Shen <hailiang@...> wrote:
|
|