In message "Re: [ruby-dev:28531] Re: Rational"
    on Mon, 10 Apr 2006 01:26:10 +0900, Shin-ichiro HARA <sinara / blade.nagaokaut.ac.jp> writes:
|
|原です。
|
|>ふなばです。
|>
|>rational/rationalize の話をしたので、原さんの rational 1.00 の
|>Rational(aFloat) と比べてみました。
|
|おお、ありがとうございます。ふなばさんのコードは参考にさせて
|いただきます。
|
|>rationalize のほうは、モノにもよりますが、rational の10倍前後遅いみた
|>いですね。なんか難しいことをしているのでしょうか。これを to_r にするの
|>は少し厳しいのかも。とりあえず、僕がみたかぎりでは、rational のほうが
|>普通っぽいようです。
|
|すいません、rationalize というのを知らないのですが、
|これは何を求める関数なのでしょう?

CommonLispには浮動小数点数を有理数に変換する関数が二つあって、
rationalは高速だが不正確(というかなんというか)で、
rationalizeは低速だがより直観的(というかなんというか)な結果
を返すそうです。以下、CLtL2からの引用です。

---
rational number
rationalize number

Each of these functions converts any non-complex number to a rational number. If the
argument is already rational, it is returned. The two functions differ in their treatment
of floating-point numbers.

rational assumes that the floating-point number is completely accurate and returns a
rational number mathematically equal to the precise value of the floating-point number.

rationalize assumes that the floating-point number is accurate only to the precision of the
floating-point representation and may return any rational number for which the
floating-point number is the best available approximation of its format; in doing this it
attempts to keep both numerator and denominator small.

It is always the case that

(float (rational x) x) == x

and

(float (rationalize x) x) == x

That is, rationalizing a floating-point number by either method and then converting it back
to a floating-point number of the same format produces the original number. What
distinguishes the two functions is that rational typically has a simple, inexpensive
implementation, whereas rationalize goes to more trouble to produce a result that is more
pleasant to view and simpler to compute with for some purposes.