Listable compiled function crashes the kernel with "no more memory available"
This bug was speedily confirmed...
Bug reported internally. Thank you! – ilian Aug 7 at 15:22
and fixed...internally at least.
Fixed in the development version. – ilian Aug 11 at 15:16
This answer is not intended to address the bug described in the OP. Rather, my goal is to address
Since
ContinuedFraction
cannot be compiled...
I don't know the exact specifics of what goes on inside ContinuedFraction[]
, so the implementation I am about to present will slightly differ in the results. Nevertheless, I think it would be useful for me to present the algorithm I use on non-Mathematica systems.
The following algorithm is due to Pyzalski and Vala. Their algorithm is based on the elementary algorithm for generating the terms of a simple continued fraction; the wrinkle is in their choice of termination criterion for stopping the iteration. You can read their paper for more details. Here is a compiled routine implementing their algorithm:
ccf = With[{m = 1*^6}, Compile[{{x, _Real}},
Module[{e = 1/m/(2 m - 1), d, f, h, n, nb, r, s, v, w},
r = IntegerPart[x]; s = Sign[x]; w = v = Abs[x - r];
f = {{1, 0}, {0, 1}};
nb = Internal`Bag[{r}];
While[True, h = 1/v; r = Floor[h];
Internal`StuffBag[nb, s r];
f = f.{{0, 1}, {1, r}};
{n, d} = f[[All, 2]];
If[Abs[w - n/d] >= e, v = h - r, Break[]]];
Internal`BagPart[nb, All]], RuntimeAttributes -> {Listable}]];
m
is an adjustable parameter that controls the termination criterion; crudely stated, ccf
stops when the denominator of the CF convergent being considered has $\approx\log_{10}(\mathtt m)$ digits.
Test:
ccf[{0.123455, 0.546452}]
{{0, 8, 9, 1, 84, 4, 7}, {0, 1, 1, 4, 1, 7, 2, 7, 6, 5, 1, 3, 1}}
ContinuedFraction[{0.123455, 0.546452}]
{{0, 8, 9, 1, 84, 4}, {0, 1, 1, 4, 1, 7, 2, 7, 6, 5, 1, 3, 1}}
ContinuedFraction[N[π]]
{3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14}
ccf[N[π]]
{3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3}
Even with the slight differences, I think ccf[]
does a good job.
(Note that with some work, one can modify ccf[]
to be a compiled substitute for Convergents[]
.)