Continued fraction/Arithmetic/Construct from rational number: Difference between revisions
Content added Content deleted
m (→{{header|C++}}) |
(added python) |
||
Line 169: | Line 169: | ||
As a silly one-liner: |
As a silly one-liner: |
||
<lang perl6>sub r2cf(Rat $x is copy) { gather $x [R/]= 1 while ($x -= take $x.floor) > 0 }</lang> |
<lang perl6>sub r2cf(Rat $x is copy) { gather $x [R/]= 1 while ($x -= take $x.floor) > 0 }</lang> |
||
=={{header|Python}}== |
|||
{{trans|Ruby}} |
|||
<lang python>def r2cf(n1,n2): |
|||
while n2: |
|||
n1, (t1, n2) = n2, divmod(n1, n2) |
|||
yield t1 |
|||
print(list(r2cf(1,2))) # => [0, 2] |
|||
print(list(r2cf(3,1))) # => [3] |
|||
print(list(r2cf(23,8))) # => [2, 1, 7] |
|||
print(list(r2cf(13,11))) # => [1, 5, 2] |
|||
print(list(r2cf(22,7))) # => [3, 7] |
|||
print(list(r2cf(14142,10000))) # => [1, 2, 2, 2, 2, 2, 1, 1, 29] |
|||
print(list(r2cf(141421,100000))) # => [1, 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2] |
|||
print(list(r2cf(1414214,1000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 3, 6, 1, 2, 1, 12] |
|||
print(list(r2cf(14142136,10000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2]</lang> |
|||
This version generates it from any real number (with rationals as a special case): |
|||
<lang python>def real2cf(x): |
|||
while True: |
|||
t1, f = divmod(x, 1) |
|||
yield int(t1) |
|||
if not f: |
|||
break |
|||
x = 1/f |
|||
from fractions import Fraction |
|||
from itertools import islice |
|||
print(list(real2cf(Fraction(13, 11)))) # => [1, 5, 2] |
|||
print(list(islice(real2cf(2 ** 0.5), 20))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |