Rational approximations
- To: mathgroup at yoda.physics.unc.edu
- Subject: Rational approximations
- From: cfw2 at po.cwru.edu (Charles F. Wells)
- Date: Wed, 6 Jan 93 17:29:56 -0500
The following code defines a command Approximate[r,k] that
calculates the rational number that best approximates the real
number r, under the constraint that the numerator and denominator
of the rational number in lowest terms each has no more than
k digits (base 10).
In[1] := RelativelyPrime[{a_,b_}] := GCD[a,b] == 1;
In[2] := RelativelyPrime[a_,b_] := RelativelyPrime[{a,b}]
In[3] := Approximate[r_, digits_Integer?Positive] :=
Module[{pairlist, lgth, bound = 10^digits-1, start, a, b, error},
start = {1,1,1-r // N // Abs};
pairlist = Select[
Flatten[Table[{a,b},{a,1,bound},{b,1,bound}],1],
RelativelyPrime];
lgth = Length[pairlist];
Do[(a = pairlist[[k]][[1]]; b = pairlist[[k]][[2]];
error = r- (a/b) // N // Abs;
If[
error < start[[3]],
start = {a,b,error}
]
),
{k,1,lgth}];
{start[[1]]/start[[2]], start[[3]]}
]
In[4] := Approximate[Pi,2]
22
Out[4] = {--, 0.00126449}
7
In[5] := Approximate[E,2]
87
Out[5] = {--, 0.000468172}
32
In[6] := Approximate[Sqrt[2],2] // Timing
99
Out[6] = {39.6 Second, {--, 0.0000721519}}
70
(This was on a 486-33 Gateway machine). I have two questions:
(1) Is there a more functional way to define Approximate?
(2) I wrote this message using EditPro, a Windows editor I just
bought so that I could cut and paste between Mathematica and text
files. The cutting and pasting worked very well, except that
I was unable to copy the "In[n]" and "Out[n]" part of the
notebook to put them into this message, so I had to type them by
hand. Is there a way to get that part of the notebook to copy too?
Charles Wells
Department of Mathematics
Case Western Reserve University
10900 Euclid Avenue
Cleveland, OH 44106-7058
216-368-2893