Hacker News new | ask | show | jobs
by a1369209993 1039 days ago
> if the underlying float representation is large enough to capture more bits than you specified when you typed in the number.

If you typed in `0.142857` (or however IEEE floats are syntaxed), the correct rational is 142857/1000000. If you want to rationalize relative to number of decimal significant digits, that should be something like `(rationalize "0.142857")` or `(rationalize (radix-mp-float 10 '(1 4 2 8 5 7) -1))`.

1 comments

> correct rational is 142857/1000000

That would be correct if the underlying representation were decimal. If it's binary, as it is in most Common Lisps,

  (rational 0.142857) --> 9586971/67108864
because the underlying representation is binary, and that denominator is 0x4000000.

My original comment about the representation being large enough to capture more bits than you specified was wrong; the unexpected behavior comes from the internal binary representation and the fact that 9586971/67108864 cannot be reduced.

If you start with integers you get

  (/ 142857 1000000) --> 142857/1000000
so you could write a version of #'rational that gives the expected base-10 result, but you'd first have to convert the float to an integer by multiplying by a power of 10.