When does the rational predicate yield false in Scheme?

Viewed 56

When is the rational? predicate useful if even (rational? (sqrt 2)) is true?

I understand that the matter of qualifying numbers rational/irrational is complicated by the fact that numbers are inexactly represented. The predicate is there, anyway.

2 Answers

In an implementation that uses floating point representation of mathematically irrational numbers, any number other than infinity or NaN will be be rational, since a floating point value is essentially a fraction with a power of 2 as the denominator. Basically, irrational numbers like π and (sqrt 2) are actually rational approximations in these systems.

The rational? predicate is provided for completeness to allow for other possible representations of irrational numbers, such as continued fractions. I don't think there are any real implementations like this, it's just theoretical.

The rational? predicate returns true if a number is a rational: a number of the form n/m where n and m are integers and m is not zero. That means that, as Barmar says, it must return true for floats (assuming the normal float representation), because floats are, in fact rationals.

But there's a really important case where rational? must return false: complex numbers. Complex numbers are not rational numbers. So for any implementation which has complex numbers, rational? will return false for those:

> (rational? 1+2i)
#f
> (number? 1+2i)
#t
> (complex? 1+2i)
#t
> (real? 1+2i)
#f
> (exact? 1+2i)
#t
> (complex? 1)
#t
> (rational? 1+0i)
#t
Related