%mathpiper,def="ContFrac"

//////////////////////////////////////////////////
/// continued fractions for polynomials
//////////////////////////////////////////////////

/// main interface
10 # ContFrac(_n) <-- ContFrac(n, 6);
50 # ContFrac(_n,_depth) <-- ContFracEval(ContFracList(n, depth), rest);

40 # ContFrac(n_CanBeUni,_depth)_(Length(VarList(n)) = 1) <--
[
  ContFracDoPoly(n,depth,VarList(n)[1]);
];

5  # ContFracDoPoly(_exp,0,_var) <-- rest;
5  # ContFracDoPoly(0,0,_var) <-- rest;
10 # ContFracDoPoly(_exp,_depth,_var) <--
[
  Local(content,exp2,first,second);
  first:=Coef(exp,var,0);
  exp:=exp-first;
  content:=Content(exp);
  exp2:=DivPoly(1,PrimitivePart(exp),var,5+3*depth)-1;
  second:=Coef(exp2,0);
  exp2 := exp2 - second;
  first+content/((1+second)+ContFracDoPoly(exp2,depth-1,var));
];

%/mathpiper



%mathpiper_docs,name="ContFrac",categories="User Functions;Numbers (Operations)"
*CMD ContFrac --- continued fraction expansion
*STD
*CALL
	ContFrac(x)
	ContFrac(x, depth)

*PARMS

{x} -- number or polynomial to expand in continued fractions

{depth} -- integer, maximum required depth of result

*DESC

This command returns the continued fraction expansion of {x}, which
should be either a floating point number or a polynomial. If
{depth} is not specified, it defaults to 6. The remainder is
denoted by {rest}.

This is especially useful for polynomials, since series expansions
that converge slowly will typically converge a lot faster if
calculated using a continued fraction expansion.

*E.G.

In> PrettyForm(ContFrac(N(Pi)))
	
	             1
	--------------------------- + 3
	           1
	----------------------- + 7
	        1
	------------------ + 15
	      1
	-------------- + 1
	   1
	-------- + 292
	rest + 1

Result: True;
In> PrettyForm(ContFrac(x^2+x+1, 3))
	
	       x
	---------------- + 1
	         x
	1 - ------------
	       x
	    -------- + 1
	    rest + 1
	
Result: True;

*SEE PAdicExpand, N
%/mathpiper_docs