String representations of numbers and approximate equality
Chris Angelico
rosuav at gmail.com
Wed Sep 24 21:38:27 EDT 2014
On Thu, Sep 25, 2014 at 5:56 AM, Dave Angel <davea at 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
More information about the Python-list
mailing list