Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #78322

Re: String representations of numbers and approximate equality

References <CAPTjJmpOxK5xosvk-=0nBdpsXoEwoSj5qEyY5pf1yFS2PbEoww@mail.gmail.com> <lvv7fq$dem$1@ger.gmane.org>
Date 2014-09-25 11:38 +1000
Subject Re: String representations of numbers and approximate equality
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.14339.1411609110.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Thu, Sep 25, 2014 at 5:56 AM, Dave Angel <davea@davea.name> wrote:
> Your definition is not nearly as concrete as you think. Is the
>  first number considered to be exact, and we'll only check the
>  second? Will the factor always be an int, and thus
>  exact?

Apologies: the definition is concrete, just under-specified in the post.

No, both numbers are inexact; most notably, one third of the factor
might be involved - both of these should be correct:

["1.333", "40"]
["1.33", "40"]

But if it's easier to assume that one or t'other must be exact, that's
fine too - I can just run the check twice, once each way.

> When the desired second number is exactly halfway between two
>  values, is rounding down as acceptable as up?
>   (Eg, exact answer 142.75, acceptable 142.7 and 142.8)

Yes, either would be accepted.

> Once you're sure of the goal, it's a question of whether the
>  decimal package can handle it. I would be inclined to do it in
>  two stages. Drop all the periods and convert each to int (long).
>  Multiply and Add 5**n, where n is related to the length of the
>  target. Convert to string,  padded with lots of zeroes.
>
>
> See if the exact string begins with the target. If not, they're
>  not close enough.
>
> If the first part passes, you just have to check the position of
>  the decimal point.
>
> Or you could check the implementation of round. If you pick the
>  right value for round,  you could do an exact comparison.
>
>
> Alternatively,  if you're just looking to catch typos,  it could
>  be simpler. Or if you put constraints on the numbers
>  involved.

It is just to catch typos. I don't mind if it misses some cases, not a big deal.

Thanks for the suggestion. I'll see how that looks in code.

ChrisA

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: String representations of numbers and approximate equality Chris Angelico <rosuav@gmail.com> - 2014-09-25 11:38 +1000

csiph-web