Mathematica 66 272 240 chars
New approach
This uses the same, reasonably efficient (59 chars), method for obtaining the smallest useful convergent of Sqrt[n]
. It takes a slightly different approach for dividing the numerator by the denominator, accurate to m
places.
t = ToString; q = QuotientRemainder;
w = FixedPoint[(# + n/# )/2 &, 1, SameTest -> (Abs[#1 - #2] < 10^(-m) &)];
r = q[Numerator@w, k = Denominator@w];
h[{c_, d_, e_}] := {Append[c, q[d, e][[1]]], 10 q[d, k][[2]], k};
t@r[[1]] <> "." <> t@FromDigits@Nest[h, {{}, 10 r[[2]], k}, m][[1]]
Example: Find the Square root of 5 accurate to 18 places
n=5; m=18;
<run the above code>
(* out *)
"2.236067977499789696"
By the way, the convergent, w, for the above case is given below.
This is still long-winded but it works.
Old approach
The following 59 chars suffice to produce a fraction that will, in decimal form, solve the problem, assuming m, n are entered programmatically:
FixedPoint[(# + n/# )/2 &, 1, SameTest -> (Abs[#1 - #2] < 10^(-m) &)]
When m=18, n=5, here's the fraction:
(* out *)
562882766124611619513723647/251728825683549488150424261
The trick is to convert this fraction into a decimal.
The easy way is to use N
;
N[%, m+1]
(* out *)
2.236067977499789696
However, N
violates the rules by specifying the precision to work with.
Back to the drawing board:
q = FixedPoint[(# + n/# )/2 &, 1, SameTest -> (Abs[#1 - #2] < 10^(-m) &)];
f[{a_, n_, d_}] :=
With[{q = QuotientRemainder[n, d]}, {Append[a, q[[1]]], q[[2]], d/10}]
StringInsert[IntegerString@FromDigits@#[[1]], ".", -1/Log[Denominator@#[[3]], 10]]
&[NestWhile[f, {{}, Numerator@q, Denominator@q}, Length@#[[1]] < m &]]
Unfortunately, it takes another 205 characters (by my reckoning) to generate a decimal expression from the fraction. Surely there must be a more direct way to divide one integer by another to m decimal places!
12345678
not1234567
(which is 1111.11070555548 according to my J program). \$\endgroup\$2 10000
output?100
? \$\endgroup\$