Numerator and denominator don't work on inexact numbers
|Reported by:||johnwcowan||Owned by:|
The R5RS and R7RS require that numerator and denominator work correctly on any rational number. That means that they should accept all inexact numbers except infinities and NaNs and return inexact results. This is not currently true either with or without the numbers egg:
#;1> (numerator 5.0) 5.0 #;2> (denominator 5.0) 1 #;3> (numerator 5.5) Error: (numerator) bad argument type - not a rational number: 5.5 Call history: <syntax> (numerator 5.5) <eval> (numerator 5.5) <-- #;4> (denominator 5.5) Error: (numerator) bad argument type - not a rational number: 5.5 Call history: <syntax> (denominator 5.5) <eval> (denominator 5.5) <--
Whereas in fact:
1 is correct
2 should return 1.0
3 should return 11.0
4 should return 2.0
In the numbers egg this is straightforward: use inexact->exact to get a ratio, use the ratio version of numerator or denominator, and then use exact->inexact to force the result to be inexact again.
Without the numbers egg, we only have flonum arithmetic. I suggest the following algorithm, which preserves the obvious invariant but doesn't always give integer results (hey, that's why we call it inexact arithmetic):
(define (denominator x) (if (integer? x) (if (exact? x) 1 1.0) (/ (- x (floor x))))) (define (numerator x) (* x (denominator x)))
Example with these definitions:
#;56> (define pi 3.1415926535898) #;57> (numerator pi) 22.1875399177921 #;58> (denominator pi) 7.0625133059307
These algorithms will return NaN if applied to an infinity or NaN.