Curious Omission In New-Style Formats

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Wed Jul 13 09:04:02 EDT 2016


Dennis Lee Bieber writes:

> On Wed, 13 Jul 2016 00:21:17 -0600, Ian Kelly <ian.g.kelly at gmail.com>
> declaimed the following:
>
>> What if I've been doing my math with fixed-point integers (because I
>> don't know about or just don't like decimals), and now I want to
>> format them for output? Is this just wrong?
>>
>>    '{:.2f}'.format(int_value / 100)
>>
>
> 	Ugh... After using integers to keep accuracy in the LSB, you
> know toss it out the window by converting to a float which may have an
> inexact representation.
>
> 	Presuming you kept track of the decimal place during all those
> integer operations, format as an integer, then split it at the decimal
> and insert a "." at the spot.

Of course floats fail (for this task) when the number exceeds their
integer range, but what would be a number within that range, preferably
well within that range, where they also fail? I didn't find any.

I tried to find one using the following code. First I found cases where
the output was different, but every single time (!) it was a bug in the
"safer" routine. Dismiss that as my incompetence, the fact remains that
the "dangerous" floating-point variant was never wrong at all while the
erroneous outputs from my "safer" formatters were off by an order of
magnitude. Floating point errors would be in the digits that matter
least.

No. The bugs were not in the regex. I was unsure of combining *? with
{1,2} that way - it never failed. I wasn't any surer of the non-regex
code - it kept failing.

import re, random

components = re.compile(r'(-?)(\d*?)(\d{1,2})')
def safer(x):
    sign, whole, decimals = components.fullmatch(str(x)).groups()
    return '{}{:>01}.{:>02}'.format(sign, whole, decimals)

def dangerouser(x):
    return '{:.2f}'.format(x/100)

for n in random.sample(range(-9000000000,9000000001), 1000000):
    x, y = safer(n), dangerouser(n)
    if x == y: continue
    print('differ:', n, x, y)



More information about the Python-list mailing list