I'm a novice Haskell user. I'm wondering how to get an approximate
value in Double of a Rational. I'm doing a little numerical
calculation using Rational to avoid truncation error, but want the
final results printed as Doubles that approximate original Rationals.
(I need this to read the results in Fortran.)
I imagine there already exists a function that returns the best
approximation in Double of a Rational, but I've failed to find one (I
looked into a documentation of Data.Ratio module, Prelude, and some
other online resources as well as "Real World Haskell"). Could
somebody help?
Regards,
Ryo
Regards,
Michael Karcher
Just as an Hint how to find that: Use Hoogle.
http://www.haskell.org/hoogle
Enter the type of the function you look for (Rational->Double).
First two hits are fromRat and fromRational. It might be that
fromRat is more efficient then fromRational, as fromRat requires
(RealFrac a) instead of just (Fractional a).
Regards,
Michael Karcher
Thank you for your response! I'll use Hoogle next time. Without
knowing fromRat[ional], I was using such a tedious function as
rat_to_frac r =
(fromIntegral (numerator r))
/ (fromIntegral (denominator r))
Regards,
Ryo
>> fromRational :: (Fractional a) => Rational -> a
> It might be that fromRat is more efficient then fromRational, as
> fromRat requires (RealFrac a) instead of just (Fractional a).
The library code uses fromRat for fromRational in the instance for
Double, so in terms of efficiency, they should be the same.
BTW, one can also convert a Double to a fraction:
Prelude> toRational pi
884279719003555%281474976710656
- Dirk
If one wants to have a series of approximants, one can use continued
fraction convergents. There is a fast algorithm on the Wikipedia page.
I have found it useful in music. For example, in my program:
> crat(cf (logBase 2 (3/2)) 8)
[0 % 1,1 % 1,1 % 2,3 % 5,7 % 12,24 % 41,31 % 53,179 % 306]
Here, "cf x n" computes n continued fractions of the Double x, and
"crat" computes the convergents: the rational numbers.
Anyway, above I computed the continued fractions of logBase 2 (3/2).
This gives the n-ET (equal temperaments) that approximates the Just
perfect fifth interval ratio 3/2 well. The numerator is the key in this
tuning. So 7%12 is recognized as key 7 in E12 (or 12-ET). The others,
E41 and E53 are also well known; the latter is used in a description of
Turkish music. E53 is such an exact approximation of Pythagorean tuning
that there is no point going higher in music.
Hans