<br><br><div class="gmail_quote">2009/8/4 James Coglan <span dir="ltr"><<a href="mailto:jcoglan@googlemail.com">jcoglan@googlemail.com</a>></span><br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
<br><br><div class="gmail_quote">2009/8/4 James Coglan <span dir="ltr"><<a href="mailto:jcoglan@googlemail.com" target="_blank">jcoglan@googlemail.com</a>></span><div><div></div><div class="h5"><br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
<br><br><div class="gmail_quote">2009/8/4 Chongkai Zhu <span dir="ltr"><<a href="mailto:czhu@cs.utah.edu" target="_blank">czhu@cs.utah.edu</a>></span><div><br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
I just checked both r5rs and r6rs. Their definition of "/simplest/ rational number" is more complex than it can be. Here's PLT's (and another system's) doc of rationalize:<br>
<br>
----<br>
(rationalize x tolerance) ? real?<br>
x : real?<br>
tolerance : real?<br>
<br>
Among the real numbers within (abs tolerance) of x, returns the one corresponding to an exact number whose denominator is smallest. If multiple integers are within tolerance of x, the one closest to 0 is used.<br>
<br>
----<br>
<br>
rationalize(x,dx)<br>
yields the rational number with smallest denominator that lies within dx of x.<br>
<br>
----<br>
<br>
in which you can see only to make the denominator smallest is enough. Is this enough hint for you to come to an algorithm?</blockquote></div><div><br>That's certainly enough of a simplification to give me an idea, though I'm not sure it'll be very efficient. I'll try to implement it and post here for feedback.</div>
</div></blockquote></div></div><div><br>This is an attempt at finding the first rational with the smallest denominator that's in range. Anyone spot anything terribly wrong with it?</div></div></blockquote><div><br>Apologies, `ceil` should have read `ceiling`:<br>
<br>(define (rationalize x tolerance)<br> (cond [(rational? x)<br> x]<br> [(not (zero? (imag-part x)))<br> (make-rectangular (rationalize (real-part x) tolerance)<br> (rationalize (imag-part x) tolerance))]<br>
[else<br> (let* ([t (abs tolerance)]<br> [a (- x t)]<br> [b (+ x t)]<br> (do ([i 1 (+ i 1)]<br> [z '()])<br> ((number? z) z)<br>
(let ([p (ceiling (* a i))]<br> [q (floor (* b i))])<br> (if (<= p q)<br> (set! z (/ (if (positive? p) p q)<br> i))))))])) <br>
</div></div><br>James<br>