Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Racket report that π is rational?

As any secondary math student can attest, pi is irrational.

And yet:

Welcome to Racket v5.3.6.
> pi
3.141592653589793
> (rational? pi)
#t

Is this because the representation of pi, in the underlying machine's floating point format, is of limited precision and therefore can always be expressed as some p/q where q is 10^n, and n is the representational precision ?

If so, how could any number thrown about by Racket (or other similarly-behaving scheme) ever be considered anything but rational? And hence, why bother with the rational? function?

UPDATE: Even (rational? (sqrt 3)) reports #t

like image 850
Ryan V. Bissell Avatar asked Oct 28 '17 05:10

Ryan V. Bissell


1 Answers

The number returned by pi is rational because the documentation says so. Specifically it says:

All numbers are complex numbers. Some of them are real numbers, and all of the real numbers that can be represented are also rational numbers, except for +inf.0 (positive infinity), +inf.f (single-precision variant), -inf.0 (negative infinity), -inf.f (single-precision variant), +nan.0 (not-a-number), and +nan.f (single-precision variant). Among the rational numbers, some are integers, because round applied to the number produces the same number.

So your hunch is right. All representable real numbers are indeed rational (except for the infinities and NaNs) because, yes, numbers are stored in fixed-size registers so the machine isn't going to store an irrational number.

As to why the Racket designers bothered with a rational? function, that is a good question. Many languages like Julia and Clojure have a real, actual, honest-to-goodness rational datatype. Racket doesn't, so, as you suspect, it does seem silly to define a near-complete subset of the reals as rationals.

But you know, it just may be convenient to have a way to talk about a non-NaN, non-Infinity value. I would have called it finite, but Racket calls it rational.

like image 172
Ray Toal Avatar answered Sep 30 '22 14:09

Ray Toal