<s> from sympy . core . numbers import Integer , Rational <EOL> def continued_fraction_periodic ( p , q , d = <NUM_LIT:0> ) : <EOL> r"""<STR_LIT>""" <EOL> from sympy . core . compatibility import as_int <EOL> from sympy . functions import sqrt <EOL> p , q , d = list ( map ( as_int , [ p , q , d ] ) ) <EOL> sd = sqrt ( d ) <EOL> if q == <NUM_LIT:0> : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> if d < <NUM_LIT:0> : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" % d ) <EOL> elif d == <NUM_LIT:0> or sd . is_integer : <EOL> return list ( continued_fraction_iterator ( Rational ( p + sd , q ) ) ) <EOL> if ( d - p ** <NUM_LIT:2> ) % q : <EOL> d *= q ** <NUM_LIT:2> <EOL> sd *= q <EOL> p *= abs ( q ) <EOL> q *= abs ( q ) <EOL> terms = [ ] <EOL> pq = { } <EOL> while ( p , q ) not in pq : <EOL> pq [ ( p , q ) ] = len ( terms ) <EOL> terms . append ( int ( ( p + sd ) / q ) ) <EOL> p = terms [ - <NUM_LIT:1> ] * q - p <EOL> q = ( d - p ** <NUM_LIT:2> ) / q <EOL> i = pq [ ( p , q ) ] <EOL> return terms [ : i ] + [ terms [ i : ] ] <EOL> def continued_fraction_reduce ( cf ) : <EOL> """<STR_LIT>""" <EOL> from sympy . core . symbol import Dummy <EOL> from sympy . solvers import solve <EOL> period = [ ] <EOL> x = Dummy ( '<STR_LIT:x>' ) <EOL> def untillist ( cf ) : <EOL> for nxt in cf : <EOL> if isinstance ( nxt , list ) : <EOL> period . extend ( nxt ) <EOL> yield x <EOL> break <EOL> yield nxt <EOL> a = Integer ( <NUM_LIT:0> ) <EOL> for a in continued_fraction_convergents ( untillist ( cf ) ) : <EOL> pass <EOL> if period : <EOL> y = Dummy ( '<STR_LIT:y>' ) <EOL> solns = solve ( continued_fraction_reduce ( period + [ y ] ) - y , y ) <EOL> solns . sort ( ) <EOL> pure = solns [ - <NUM_LIT:1> ] <EOL> return a . subs ( x , pure ) . radsimp ( ) <EOL> else : <EOL> return a <EOL> def continued_fraction_iterator ( x ) : <EOL> """<STR_LIT>""" <EOL> from sympy . functions import floor <EOL> while True : <EOL> i = floor ( x ) <EOL> yield i <EOL> x -= i <EOL> if not x : <EOL> break <EOL> x = <NUM_LIT:1> / x <EOL> def continued_fraction_convergents ( cf ) : <EOL> """<STR_LIT>""" <EOL> p_2 , q_2 = Integer ( <NUM_LIT:0> ) , Integer ( <NUM_LIT:1> ) <EOL> p_1 , q_1 = Integer ( <NUM_LIT:1> ) , Integer ( <NUM_LIT:0> ) <EOL> for a in cf : <EOL> p , q = a * p_1 + p_2 , a * q_1 + q_2 <EOL> p_2 , q_2 = p_1 , q_1 <EOL> p_1 , q_1 = p , q <EOL> yield p / q </s>
