Opened 5 years ago
Closed 5 years ago
#1016 closed defect (fixed)
Numerator and denominator don't work on inexact numbers
Reported by: | johnwcowan | Owned by: | |
---|---|---|---|
Priority: | major | Milestone: | someday |
Component: | unknown | Version: | 4.8.x |
Keywords: | Cc: | ||
Estimated difficulty: |
Description
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.
Change History (2)
comment:1 Changed 5 years ago by sjamaan
comment:2 Changed 5 years ago by sjamaan
- Resolution set to fixed
- Status changed from new to closed
And fixed in the numbers egg in revision [29280].
Numbers 2.8.2 includes this fix.
Fixed in core by revision 38c5af40478da43d72502402b94d9d42ea5cf2a8