[Tutor] Fraction - differing interpretations for number and string - presentation
Steven D'Aprano
steve at pearwood.info
Fri Apr 17 04:29:10 CEST 2015
On Thu, Apr 16, 2015 at 03:11:59PM -0700, Jim Mooney wrote:
> So the longer numerator and denominator would, indeed, be more accurate if
> used in certain calculations rather than being normalized to a float - such
> as in a Fortran subroutine or perhaps if exported to a machine with a
> longer bit-length? That's mainly what I was interested in - if there is any
> usable difference between the two results.
You're asking simple questions that have complicated answers which
probably won't be what you are looking for. But let's try :-)
Let's calculate a number. The details don't matter:
x = some_calculation(a, b)
print(x)
which prints 1.64. Great, we have a number that is the closest possible
base 2 float to the decimal 164/100. If we convert that float to a
fraction *exactly*, we get:
py> Fraction(1.64)
Fraction(7385903388887613, 4503599627370496)
So the binary float which displays as 1.64 is *actually* equal to
7385903388887613/4503599627370496, which is just a tiny bit less than
the decimal 1.64:
py> Fraction(1.64) - Fraction("1.64")
Fraction(-11, 112589990684262400)
That's pretty close. The decimal value that normally displays as 1.64 is
perhaps more accurately displayed as:
py> "%.23f" % 1.64
'1.63999999999999990230037'
but even that is not exact.
So which is the "right" answer? That depends.
(1) It could be that our initial calculation some_calculation(a, b)
actually was 164/100, say, in which case the *correct* result should be
decimal 1.64 = Fraction("1.64") and the 7385blahblahblah/blahblahblah is
just an artifact of the fact that floats are binary.
(2) Or it could be that the some_calculation(a, b) result actually was
7385903388887613/4503599627370496, say, in which case it is a mere
coincidence that this number displays as 1.64 when treated as a binary
float. The long 7385blahblahblah numerator and denominator is exactly
correct, and decimal 1.64 is a approximation.
There is no way of telling in advance which interpretation is correct.
You need to think about the calculation you performed and decide what it
means, not just look at the final result.
Although... 9 times out of 10, if you get something *close* to an exact
decimal, a coincidence is not likely. If you get exactly 0.5 out of a
calculation, rather than 0.5000000000001, then it probably should be
exactly 1/2. *Probably*. The reality is that very often, the difference
isn't that important. The difference between
1.64 inches
and
1.63999999999999990230037 inches
is probably not going to matter, especially if you are cutting the
timber with a chainsaw.
--
Steve
More information about the Tutor
mailing list