Always false float comparisons

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Wed May 18 16:42:09 PDT 2016


On Wed, May 18, 2016 at 04:09:28PM -0700, Walter Bright via Digitalmars-d wrote:
[...]
> Now try the square root of 2. Or pi, e, etc. The irrational numbers
> are, by definition, not representable as a ratio.

This is somewhat tangential, but in certain applications it is perfectly
possible to represent certain irrationals exactly. For example, if
you're working with quadratic fractions of the form a + b*sqrt(r) where
r is fixed, you can exactly represent all such numbers as a pair of
rational coefficients. These numbers are closed under addition,
subtraction, multiplication, and division, so you have a nice closed
system that can handle numbers that contain square roots.

It is possible to have multiple square roots (e.g., a + b*sqrt(r) +
c*sqrt(s) + d*sqrt(r*s)), but the tuple gets exponentially long with
each different root, so it quickly becomes unwieldy (not to mention
slow).

Similar techniques can be used for exactly representing roots of cubic
equations (including cube roots) -- a single cubic root can be
represented as a 3-tuple -- or higher. Again, these are closed under +,
*, -, /, so you can do quite a lot of interesting things with them
without sacrificing exact arithmetic. Though again, things quickly
become unwieldy.  Higher order roots are also possible, though of
questionable value since storage and performance costs quickly become
too high.

Transcendentals like pi or e are out of reach by this method, though.
You'd need a variable-length vector to represent numbers that contain pi
or e as a factor, because their powers never become integral, so you
potentially need to represent an arbitrary power of pi in order to
obtain closure under + and *.

Of course, with increasing sophistication the computation and storage
costs increase accordingly, but the point is that if your application is
known to only need a certain subset of irrationals, it may well be
possible to represent them exactly within reasonable costs. (There's
also RealLib, that can exactly represent *all* computable reals, but may
not be feasible depending on what your application does.)


T

-- 
Let's eat some disquits while we format the biskettes.


More information about the Digitalmars-d mailing list