Summary

Numerator and denominator don't work on inexact numbers

Metadata

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.

Changes and comments

[2013-06-29 18:19:25 UTC] sjamaan wrote:

Fixed in core by revision 38c5af40478da43d72502402b94d9d42ea5cf2a8

[2013-06-29 20:17:08 UTC] sjamaan changed status from new to closed

[2013-06-29 20:17:08 UTC] sjamaan set resolution to fixed

[2013-06-29 20:17:08 UTC] sjamaan wrote:

And fixed in the numbers egg in revision [[29280]|].

Numbers 2.8.2 includes this fix.