[math-fun] Fwd: [CASE:520044] Documented bug(s) in Rationalize
Another chance for funsters to take sides. On 12/16/2013, 03:30pm, Bill Gosper wrote: Doc: "Rationalize[x,dx] yields the rational number with smallest denominator that lies within dx of x." First of all, is this strictly between, or inclusive of the endpoints? I can't tell because it's broken: Doc: "Successive rational approximations to π: In[1]:= Table[Rationalize[Pi, 10^-n], {n, 1, 10}] Out[1]= {22/7, 22/7, 201/64, 333/106, 355/113, 355/113, 75948/24175, \ 100798/32085, 103993/33102, 312689/99532}" The first ratio should be 16/5 ! |π - 16/5| < 1/10 Simpler case: In[117]:= Rationalize[1/4, 1/11] Out[117]= 1/4 should be 1/3, which should also be the answer to Rationalize[1/4, 1/12] if "within" is not strictly. The following code, which includes the "Strict" option seems to work. It also includes the Mediant function, which Mathematica should offer. ratinint[hi_,lo_]/;hi>lo:=ratinint[lo,hi]; ratinint[lo_,hi_]:=Block[{M={{1,0},{0,1}},k}, While[{{1,0},{0,1}}!=(k=Floor[{{1,-Divide@@(M.{1,-hi})}, {-Divide@@Reverse[M.{1,-lo}],1}}]),M=k.M];Mediant@@(Divide@@#&/@M)] rationalize[x_,dx_,Strict]:=ratinint[x-dx,x+dx]; rationalize[x_?NumericQ,dx_]:=Block[{M=IdentityMatrix[2],d=dx}, NestWhile[(M=(M.{{#,1},{1,0}}&)@Floor[#]; d=-d;1/Mod[#,1])&,x,Abs[x*M[[2,1]]-M[[1,1]]]>Abs[M[[2,1]]*dx]&]; Divide@@(M.{1,-#})&@Floor[Divide@@({1,-d-x}.M)]] Mediant[a__] := Divide @@ (Plus @@ # & /@ {Numerator[{a}], Denominator[{a}]}) (It also harmlessly divides by 0.) My second issue is much deeper, and we may want to split it off as a separate discussion. Doc: "No rational number is by default considered "close enough" to N[Pi]: In[1]:= Rationalize[N[Pi]] Out[1]= 3.14159 Force a rational approximation to be found: In[1]:= Rationalize[N[Pi], 0] Out[1]= 245850922/78256779 " No! Mathematica is perpetrating the pernicious delusion that it has "inexact numbers". In fact, ALL things NumberQ are exact, dyadic rationals (or the Complex of two such). "Inexact" numbers are really exact quantities subject to *inexact operations*. "Force a rational approximation to be found" should actually say "Subject N[π], which is already a rational approximation, to a mysterious reapproximation in which the denominator is minimal wrt some inexplicit accuracy bound." On the MacBook Pro, at least, the actual exact value of N[π] is 884279719003555/2^48, and it is very unhelpful to conceal this fact. The subterfuge gets even more frustrating with quantities like N[π,69]. --Bill Gosper
participants (1)
-
Bill Gosper