for / while else doesn't make sense
Ben Bacarisse
ben.usenet at bsb.me.uk
Mon May 23 17:01:49 EDT 2016
Mark Dickinson <mdickinson at enthought.com> writes:
> Ben Bacarisse <ben.usenet <at> bsb.me.uk> writes:
>> [1] Not being a Python expert I don't know how you show that actual
>> value of a float. What is the Pythonic way to do that?
>
> I don't know about Pythonic, but here are some options.
>
> 1. Convert the float to Decimal, and print the result. This shows
> the exact binary value that's stored, but displays it in decimal.
> Be aware that the result will be hundreds of digits long for
> very large or very small floats.
>
> >>> print(Decimal(pi))
> 3.141592653589793115997963468544185161590576171875
>
> 2. If you're happy with a hexadecimal representation, use the
> float.hex method. Again, this shows the exact value stored.
>
> >>> print(pi.hex())
> 0x1.921fb54442d18p+1
>
> 3. To get an equivalent fraction, convert to the fractions.Fraction
> type or use the as_integer_ratio method.
>
> >>> from fractions import Fraction
> >>> print(Fraction(pi))
> 884279719003555/281474976710656
> >>> print(pi.as_integer_ratio())
> (884279719003555, 281474976710656)
Thanks.
I worked out 1 and 3 after posting but I was not aware of how to get 2
in Python. It's the format I am most familiar with (and it's very
compact for numbers that are anything but in decimal or as fractions)
so that's handy.
Once you told me that hex() does the trick I wondered if "%x" % 3.4
would give me 0x1.b333333333333p+1 but the float is converted to the
expected integer. I doubt anyone relies on using %x for the integer
part of a float so maybe %x could be provided for floats...
--
Ben.
More information about the Python-list
mailing list