rational, rationalize
rational, rationalize Function
Syntax:
rational number → rational
rationalize number → rational
Arguments and Values:
number—a real.
rational—a rational.
Description:
rational and rationalize convert reals to rationals.
If number is already rational, it is returned.
If number is a float, rational returns a rational that is mathematically equal in value to the float. rationalize returns a rational that approximates the float to the accuracy of the underlying floating-point representation.
rational assumes that the float is completely accurate.
rationalize assumes that the float is accurate only to the precision of the floating-point representation.
Examples:
(rational 0) → 0
(rationalize -11/100) → -11/100
(rational .1) → 13421773/134217728 ;implementation-dependent
(rationalize .1) → 1/10
Affected By:
The implementation.
Exceptional Situations:
Should signal an error of type type-error if number is not a real. Might signal arithmetic-error.
Notes:
It is always the case that
(float (rational x) x) ≡ x
and
(float (rationalize x) x) ≡ x
That is, rationalizing a float by either method and then converting it back to a float of the same format produces the original number.
Expanded Reference: rational, rationalize
Converting floats with rational
rational converts a float to a rational that is mathematically exactly equal to the float's value. Since floats are stored in binary, the result can have a large denominator.
(rational 0)
=> 0
(rational 0.5)
=> 1/2
(rational 0.25)
=> 1/4
(rational .1)
=> 13421773/134217728
Converting floats with rationalize
rationalize finds a simpler rational approximation that is within the floating-point precision of the input.
(rationalize 0.5)
=> 1/2
(rationalize 0.1)
=> 1/10
(rationalize 0.33)
=> 33/100
Difference between rational and rationalize
The key distinction is that rational treats the float as exact, while rationalize accounts for float imprecision.
;; 0.1 cannot be exactly represented in binary floating point
(rational 0.1)
=> 13421773/134217728
(rationalize 0.1)
=> 1/10
;; Both give the same result when the float is exact
(rational 0.5)
=> 1/2
(rationalize 0.5)
=> 1/2
Identity for rational inputs
If the argument is already rational (integer or ratio), both functions return it unchanged.
(rational 5)
=> 5
(rationalize 5)
=> 5
(rational 3/7)
=> 3/7
(rationalize 3/7)
=> 3/7
(rationalize -11/100)
=> -11/100
Round-trip guarantee
Converting to rational and back to float always recovers the original float.
(float (rational 3.14) 1.0)
=> 3.14
(float (rationalize 3.14) 1.0)
=> 3.14