Continued fraction/Arithmetic/Construct from rational number: Difference between revisions
Content added Content deleted
(Added a Scheme implementation.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 37: | Line 37: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F r2cf(=n1, =n2) |
||
[Int] r |
[Int] r |
||
L n2 != 0 |
L n2 != 0 |
||
Line 53: | Line 53: | ||
print(r2cf(141421, 100000)) |
print(r2cf(141421, 100000)) |
||
print(r2cf(1414214, 1000000)) |
print(r2cf(1414214, 1000000)) |
||
print(r2cf(14142136, 10000000))</ |
print(r2cf(14142136, 10000000))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 73: | Line 73: | ||
The continued fraction expansion of -151/77 is sensitive to whether the language modulo operator follows the mathematical definition or the C definition.<br> |
The continued fraction expansion of -151/77 is sensitive to whether the language modulo operator follows the mathematical definition or the C definition.<br> |
||
Algol 68's MOD operator uses the mathematical definition (rounds towards -infinity), so the results for -157//77 agree with the EDSAC, J and a few other sdamples. Most other samples calculate the remainder using the C definotion. |
Algol 68's MOD operator uses the mathematical definition (rounds towards -infinity), so the results for -157//77 agree with the EDSAC, J and a few other sdamples. Most other samples calculate the remainder using the C definotion. |
||
< |
<syntaxhighlight lang="algol68">BEGIN # construct continued fraction representations of rational numbers # |
||
# Translated from the C sample # |
# Translated from the C sample # |
||
# Uses code from the Arithmetic/Rational task # |
# Uses code from the Arithmetic/Rational task # |
||
Line 155: | Line 155: | ||
show r2cf( "Running for pi :", pi ) |
show r2cf( "Running for pi :", pi ) |
||
END |
END |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 186: | Line 186: | ||
C does not implement Lazy evaluation and it is this particular feature which is the real challenge of this particular example. It can however be simulated. The following example uses pointers. It seems that the same data is being passed but since the function accepts pointers, the variables are being changed. One other way to simulate laziness would be to use global variables. Then although it would seem that the same values are being passed even as constants, the job is actually getting done. In my view, that would be plain cheating. |
C does not implement Lazy evaluation and it is this particular feature which is the real challenge of this particular example. It can however be simulated. The following example uses pointers. It seems that the same data is being passed but since the function accepts pointers, the variables are being changed. One other way to simulate laziness would be to use global variables. Then although it would seem that the same values are being passed even as constants, the job is actually getting done. In my view, that would be plain cheating. |
||
<syntaxhighlight lang="c"> |
|||
<lang C> |
|||
#include<stdio.h> |
#include<stdio.h> |
||
Line 257: | Line 257: | ||
} |
} |
||
</ |
</syntaxhighlight> |
||
And the run gives : |
And the run gives : |
||
<pre> |
<pre> |
||
Line 286: | Line 286: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
Line 331: | Line 331: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output |
Output |
||
<pre> |
<pre> |
||
Line 357: | Line 357: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
/* Interface for all Continued Fractions |
/* Interface for all Continued Fractions |
||
Nigel Galloway, February 9th., 2013. |
Nigel Galloway, February 9th., 2013. |
||
Line 388: | Line 388: | ||
const int nextTerm() {if (first) {first = false; return 1;} else return 2;} |
const int nextTerm() {if (first) {first = false; return 1;} else return 2;} |
||
const bool moreTerms() {return true;} |
const bool moreTerms() {return true;} |
||
};</ |
};</syntaxhighlight> |
||
===Testing=== |
===Testing=== |
||
====1/2 3 23/8 13/11 22/7 -151/77==== |
====1/2 3 23/8 13/11 22/7 -151/77==== |
||
< |
<syntaxhighlight lang="cpp">int main() { |
||
for(r2cf n(1,2); n.moreTerms(); std::cout << n.nextTerm() << " "); |
for(r2cf n(1,2); n.moreTerms(); std::cout << n.nextTerm() << " "); |
||
std::cout << std::endl; |
std::cout << std::endl; |
||
Line 405: | Line 405: | ||
std::cout << std::endl; |
std::cout << std::endl; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 416: | Line 416: | ||
</pre> |
</pre> |
||
====<math>\sqrt 2</math>==== |
====<math>\sqrt 2</math>==== |
||
< |
<syntaxhighlight lang="cpp">int main() { |
||
int i = 0; |
int i = 0; |
||
for(SQRT2 n; i++ < 20; std::cout << n.nextTerm() << " "); |
for(SQRT2 n; i++ < 20; std::cout << n.nextTerm() << " "); |
||
Line 425: | Line 425: | ||
std::cout << std::endl; |
std::cout << std::endl; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 433: | Line 433: | ||
</pre> |
</pre> |
||
====Real approximations of a rational number==== |
====Real approximations of a rational number==== |
||
< |
<syntaxhighlight lang="cpp">int main() { |
||
for(r2cf n(31,10); n.moreTerms(); std::cout << n.nextTerm() << " "); |
for(r2cf n(31,10); n.moreTerms(); std::cout << n.nextTerm() << " "); |
||
std::cout << std::endl; |
std::cout << std::endl; |
||
Line 451: | Line 451: | ||
std::cout << std::endl; |
std::cout << std::endl; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 465: | Line 465: | ||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(defn r2cf [n d] |
||
(if-not (= d 0) (cons (quot n d) (lazy-seq (r2cf d (rem n d)))))) |
(if-not (= d 0) (cons (quot n d) (lazy-seq (r2cf d (rem n d)))))) |
||
Line 491: | Line 491: | ||
(doseq [inputs demo |
(doseq [inputs demo |
||
:let [outputs (r2cf (first inputs) (last inputs))]] |
:let [outputs (r2cf (first inputs) (last inputs))]] |
||
(println inputs ";" outputs))</ |
(println inputs ";" outputs))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 517: | Line 517: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun r2cf (n1 n2) |
||
(lambda () |
(lambda () |
||
(unless (zerop n2) |
(unless (zerop n2) |
||
Line 557: | Line 557: | ||
(31428571 10000000) |
(31428571 10000000) |
||
(314285714 100000000) |
(314285714 100000000) |
||
(3141592653589793 1000000000000000)))</ |
(3141592653589793 1000000000000000)))</syntaxhighlight> |
||
Output: |
Output: |
||
Line 583: | Line 583: | ||
=={{header|D}}== |
=={{header|D}}== |
||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
< |
<syntaxhighlight lang="d">import std.concurrency; |
||
import std.stdio; |
import std.stdio; |
||
Line 654: | Line 654: | ||
frac.r2cf.iterate; |
frac.r2cf.iterate; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 683: | Line 683: | ||
Besides the assigned task, this program demonstrates a division subroutine |
Besides the assigned task, this program demonstrates a division subroutine |
||
for 35-bit positive integers, returning quotient and remainder. |
for 35-bit positive integers, returning quotient and remainder. |
||
< |
<syntaxhighlight lang="edsac"> |
||
[Continued fractions from rationals. |
[Continued fractions from rationals. |
||
EDSAC program, Initial Orders 2.] |
EDSAC program, Initial Orders 2.] |
||
Line 924: | Line 924: | ||
E 13 Z [define entry point] |
E 13 Z [define entry point] |
||
P F [acc = 0 on entry] |
P F [acc = 0 on entry] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 939: | Line 939: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">let rec r2cf n d = |
||
if d = LanguagePrimitives.GenericZero then [] |
if d = LanguagePrimitives.GenericZero then [] |
||
else let q = n / d in q :: (r2cf d (n - q * d)) |
else let q = n / d in q :: (r2cf d (n - q * d)) |
||
Line 957: | Line 957: | ||
printfn "%A" (r2cf 1414214 1000000) |
printfn "%A" (r2cf 1414214 1000000) |
||
printfn "%A" (r2cf 14142136 10000000) |
printfn "%A" (r2cf 14142136 10000000) |
||
0</ |
0</syntaxhighlight> |
||
Output |
Output |
||
<pre>[0; 2] |
<pre>[0; 2] |
||
Line 972: | Line 972: | ||
[1; 2; 2; 2; 2; 2; 2; 2; 2; 2; 6; 1; 2; 4; 1; 1; 2]</pre> |
[1; 2; 2; 2; 2; 2; 2; 2; 2; 2; 6; 1; 2; 4; 1; 1; 2]</pre> |
||
;A version for larger numerators and denominators. |
;A version for larger numerators and denominators. |
||
< |
<syntaxhighlight lang="fsharp"> |
||
let rec rI2cf n d = |
let rec rI2cf n d = |
||
if d = 0I then [] |
if d = 0I then [] |
||
else let q = n / d in (decimal)q :: (rI2cf d (n - q * d)) |
else let q = n / d in (decimal)q :: (rI2cf d (n - q * d)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Note that the input values are stored as strings and converted to numbers before being fed to <code>r2cf</code>. This is because ratios automatically reduce themselves to the lowest-terms mixed number, which would make for confusing output in this instance. |
Note that the input values are stored as strings and converted to numbers before being fed to <code>r2cf</code>. This is because ratios automatically reduce themselves to the lowest-terms mixed number, which would make for confusing output in this instance. |
||
< |
<syntaxhighlight lang="factor">USING: formatting kernel lists lists.lazy math math.parser qw |
||
sequences ; |
sequences ; |
||
IN: rosetta-code.cf-arithmetic |
IN: rosetta-code.cf-arithmetic |
||
Line 1,012: | Line 1,012: | ||
each ; |
each ; |
||
MAIN: main</ |
MAIN: main</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,039: | Line 1,039: | ||
{{works with|gforth|0.7.3}} |
{{works with|gforth|0.7.3}} |
||
< |
<syntaxhighlight lang="forth">: r2cf ( num1 den1 -- num2 den2 ) swap over >r s>d r> sm/rem . ; |
||
: .r2cf ( num den -- ) |
: .r2cf ( num den -- ) |
||
Line 1,067: | Line 1,067: | ||
314285714 100000000 .r2cf |
314285714 100000000 .r2cf |
||
3141592653589793 1000000000000000 .r2cf ; |
3141592653589793 1000000000000000 .r2cf ; |
||
r2cf-demo</ |
r2cf-demo</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,093: | Line 1,093: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic"> |
||
'with some other constants |
'with some other constants |
||
data 1,2, 21,7, 21,-7, 7,21, -7,21 |
data 1,2, 21,7, 21,-7, 7,21, -7,21 |
||
Line 1,151: | Line 1,151: | ||
sleep |
sleep |
||
system |
system |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,190: | Line 1,190: | ||
File <code>cf.go</code>: |
File <code>cf.go</code>: |
||
< |
<syntaxhighlight lang="go">package cf |
||
import ( |
import ( |
||
Line 1,264: | Line 1,264: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
File <code>rat.go</code>: |
File <code>rat.go</code>: |
||
< |
<syntaxhighlight lang="go">package cf |
||
import "fmt" |
import "fmt" |
||
Line 1,296: | Line 1,296: | ||
// Rosetta Code task explicitly asked for this function, |
// Rosetta Code task explicitly asked for this function, |
||
// so here it is. We'll just use the types above instead. |
// so here it is. We'll just use the types above instead. |
||
func r2cf(n1, n2 int64) ContinuedFraction { return Rat{n1, n2}.CFTerms }</ |
func r2cf(n1, n2 int64) ContinuedFraction { return Rat{n1, n2}.CFTerms }</syntaxhighlight> |
||
File <code>rat_test.go</code>: |
File <code>rat_test.go</code>: |
||
< |
<syntaxhighlight lang="go">package cf |
||
import ( |
import ( |
||
Line 1,344: | Line 1,344: | ||
// [… commented output used by go test omitted for |
// [… commented output used by go test omitted for |
||
// Rosetta Code listing; it is the same as below …] |
// Rosetta Code listing; it is the same as below …] |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,390: | Line 1,390: | ||
{{trans|Python}} |
{{trans|Python}} |
||
This more general version generates a continued fraction from any real number (with rationals as a special case): |
This more general version generates a continued fraction from any real number (with rationals as a special case): |
||
< |
<syntaxhighlight lang="haskell">import Data.Ratio ((%)) |
||
real2cf :: (RealFrac a, Integral b) => a -> [b] |
real2cf :: (RealFrac a, Integral b) => a -> [b] |
||
Line 1,406: | Line 1,406: | ||
[ real2cf (13 % 11) |
[ real2cf (13 % 11) |
||
, take 20 $ real2cf (sqrt 2) |
, take 20 $ real2cf (sqrt 2) |
||
]</ |
]</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>[1,5,2] |
<pre>[1,5,2] |
||
Line 1,417: | Line 1,417: | ||
This version is a modification of an explicit version shown in http://www.jsoftware.com/jwiki/Essays/Continued%20Fractions to comply with the task specifications. |
This version is a modification of an explicit version shown in http://www.jsoftware.com/jwiki/Essays/Continued%20Fractions to comply with the task specifications. |
||
< |
<syntaxhighlight lang="j">cf=: _1 1 ,@}. (, <.)@%@-/ ::]^:a:@(, <.)@(%&x:/)</syntaxhighlight> |
||
==== Examples ==== |
==== Examples ==== |
||
< |
<syntaxhighlight lang="j"> cf each 1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77 |
||
┌───┬─┬─────┬─────┬───┬─────────────────────────────────┬─────────┐ |
┌───┬─┬─────┬─────┬───┬─────────────────────────────────┬─────────┐ |
||
│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│_2 25 1 2│ |
│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│_2 25 1 2│ |
||
Line 1,430: | Line 1,430: | ||
┌────┬─────┬──────────┬───────┬────────┬──────────┬────────────┬───────────┐ |
┌────┬─────┬──────────┬───────┬────────┬──────────┬────────────┬───────────┐ |
||
│3 10│3 7 7│3 7 23 1 2│3 7 357│3 7 2857│3 7 142857│3 7 476190 3│3 7 7142857│ |
│3 10│3 7 7│3 7 23 1 2│3 7 357│3 7 2857│3 7 142857│3 7 476190 3│3 7 7142857│ |
||
└────┴─────┴──────────┴───────┴────────┴──────────┴────────────┴───────────┘</ |
└────┴─────┴──────────┴───────┴────────┴──────────┴────────────┴───────────┘</syntaxhighlight> |
||
This tacit version first produces the answer with a trailing ∞ (represented by _ in J) which is then removed by the last operation (_1 1 ,@}. ...). A continued fraction can be evaluated using the verb ((+%)/) and both representations produce equal results, |
This tacit version first produces the answer with a trailing ∞ (represented by _ in J) which is then removed by the last operation (_1 1 ,@}. ...). A continued fraction can be evaluated using the verb ((+%)/) and both representations produce equal results, |
||
< |
<syntaxhighlight lang="j"> 3 7 =&((+ %)/) 3 7 _ |
||
1</ |
1</syntaxhighlight> |
||
Incidentally, J and Tcl report a different representation for -151/77 versus the representation of some other implementations; however, both representations produce equal results. |
Incidentally, J and Tcl report a different representation for -151/77 versus the representation of some other implementations; however, both representations produce equal results. |
||
< |
<syntaxhighlight lang="j"> _2 25 1 2 =&((+ %)/) _1 _1 _24 _1 _2 |
||
1</ |
1</syntaxhighlight> |
||
===Tacit version 2=== |
===Tacit version 2=== |
||
Line 1,442: | Line 1,442: | ||
Translation of python |
Translation of python |
||
< |
<syntaxhighlight lang="j">r2cf=:1 1{."1@}.({:,(0,{:)#:{.)^:(*@{:)^:a:</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="j"> ((":@{.,'/',":@{:),': ',":@r2cf)@>1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77;14142 10000;141421 100000;1414214 1000000;14142136 10000000;31 10;314 100;3142 1000;31428 10000;314285 100000;3142857 1000000;31428571 10000000;314285714 100000000 |
||
1/2: 0 2 |
1/2: 0 2 |
||
3/1: 3 |
3/1: 3 |
||
Line 1,465: | Line 1,465: | ||
3142857/1000000: 3 7 142857 |
3142857/1000000: 3 7 142857 |
||
31428571/10000000: 3 7 476190 3 |
31428571/10000000: 3 7 476190 3 |
||
314285714/100000000: 3 7 7142857 </ |
314285714/100000000: 3 7 7142857 </syntaxhighlight> |
||
===Explicit versions=== |
===Explicit versions=== |
||
==== version 1 ==== |
==== version 1 ==== |
||
Implemented as a class, r2cf preserves state in a separate locale. I've used some contrivances to jam the examples onto one line. |
Implemented as a class, r2cf preserves state in a separate locale. I've used some contrivances to jam the examples onto one line. |
||
<syntaxhighlight lang="j"> |
|||
<lang J> |
|||
coclass'cf' |
coclass'cf' |
||
create =: dyad def 'EMPTY [ N =: x , y' |
create =: dyad def 'EMPTY [ N =: x , y' |
||
Line 1,503: | Line 1,503: | ||
│_151 77 │_2 25 1 2 │ |
│_151 77 │_2 25 1 2 │ |
||
└─────────────────┴─────────────────────────────────┘ |
└─────────────────┴─────────────────────────────────┘ |
||
)</ |
)</syntaxhighlight> |
||
==== version 2 ==== |
==== version 2 ==== |
||
<syntaxhighlight lang="j"> |
|||
<lang J> |
|||
f =: 3 : 0 |
f =: 3 : 0 |
||
a =. {.y |
a =. {.y |
||
Line 1,518: | Line 1,518: | ||
┌───┬─┬─────┬─────┬───┬───────────────────────────────────┬─────────┐ |
┌───┬─┬─────┬─────┬───┬───────────────────────────────────┬─────────┐ |
||
│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2 _│_2 25 1 2│ |
│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2 _│_2 25 1 2│ |
||
└───┴─┴─────┴─────┴───┴───────────────────────────────────┴─────────┘</ |
└───┴─┴─────┴─────┴───┴───────────────────────────────────┴─────────┘</syntaxhighlight> |
||
==== version 3 ==== |
==== version 3 ==== |
||
Line 1,524: | Line 1,524: | ||
translation of python: |
translation of python: |
||
< |
<syntaxhighlight lang="j">r2cf=:3 :0 |
||
'n1 n2'=. y |
'n1 n2'=. y |
||
r=.'' |
r=.'' |
||
Line 1,531: | Line 1,531: | ||
r=.r,t1 |
r=.r,t1 |
||
end. |
end. |
||
)</ |
)</syntaxhighlight> |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="j"> r2cf each 1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77 |
||
┌───┬─┬─────┬─────┬───┬─────────────────────────────────┬─────────┐ |
┌───┬─┬─────┬─────┬───┬─────────────────────────────────┬─────────┐ |
||
│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│_2 25 1 2│ |
│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│_2 25 1 2│ |
||
└───┴─┴─────┴─────┴───┴─────────────────────────────────┴─────────┘</ |
└───┴─┴─────┴─────┴───┴─────────────────────────────────┴─────────┘</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
{{works with|Java|9}} |
{{works with|Java|9}} |
||
< |
<syntaxhighlight lang="java">import java.util.Iterator; |
||
import java.util.List; |
import java.util.List; |
||
import java.util.Map; |
import java.util.Map; |
||
Line 1,619: | Line 1,619: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1 / 2 = 0 2 |
<pre> 1 / 2 = 0 2 |
||
Line 1,648: | Line 1,648: | ||
{{works with|Julia|0.6}} |
{{works with|Julia|0.6}} |
||
< |
<syntaxhighlight lang="julia"># It'st most appropriate to define a Julia iterable object for this task |
||
# Julia doesn't have Python'st yield, the closest to it is produce/consume calls with Julia tasks |
# Julia doesn't have Python'st yield, the closest to it is produce/consume calls with Julia tasks |
||
# but for various reasons they don't work out for this task |
# but for various reasons they don't work out for this task |
||
Line 1,702: | Line 1,702: | ||
println(collect(ContinuedFraction(13 // 11))) # => [1, 5, 2] |
println(collect(ContinuedFraction(13 // 11))) # => [1, 5, 2] |
||
println(collect(ContinuedFraction(√2), 20)) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]</ |
println(collect(ContinuedFraction(√2), 20)) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.1.2 |
||
// compile with -Xcoroutines=enable flag from command line |
// compile with -Xcoroutines=enable flag from command line |
||
Line 1,749: | Line 1,749: | ||
iterate(r2cf(frac)) |
iterate(r2cf(frac)) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,779: | Line 1,779: | ||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
Mathematica has a build-in function ContinuedFraction. |
Mathematica has a build-in function ContinuedFraction. |
||
< |
<syntaxhighlight lang="mathematica">ContinuedFraction[1/2] |
||
ContinuedFraction[3] |
ContinuedFraction[3] |
||
ContinuedFraction[23/8] |
ContinuedFraction[23/8] |
||
Line 1,788: | Line 1,788: | ||
ContinuedFraction[141421/100000] |
ContinuedFraction[141421/100000] |
||
ContinuedFraction[1414214/1000000] |
ContinuedFraction[1414214/1000000] |
||
ContinuedFraction[14142136/10000000]</ |
ContinuedFraction[14142136/10000000]</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>{0, 2} |
<pre>{0, 2} |
||
Line 1,802: | Line 1,802: | ||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">MODULE ConstructFromrationalNumber; |
||
FROM FormatString IMPORT FormatString; |
FROM FormatString IMPORT FormatString; |
||
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
||
Line 1,877: | Line 1,877: | ||
ReadChar; |
ReadChar; |
||
END ConstructFromrationalNumber.</ |
END ConstructFromrationalNumber.</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">iterator r2cf*(n1, n2: int): int = |
||
var (n1, n2) = (n1, n2) |
var (n1, n2) = (n1, n2) |
||
while n2 != 0: |
while n2 != 0: |
||
Line 1,903: | Line 1,903: | ||
for pair in [(31,10), (314,100), (3142,1000), (31428,10000), (314285,100000), |
for pair in [(31,10), (314,100), (3142,1000), (31428,10000), (314285,100000), |
||
(3142857,1000000), (31428571,10000000), (314285714,100000000)]: |
(3142857,1000000), (31428571,10000000), (314285714,100000000)]: |
||
echo pair, " -> ", toSeq(r2cf(pair[0], pair[1]))</ |
echo pair, " -> ", toSeq(r2cf(pair[0], pair[1]))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,928: | Line 1,928: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">apply(contfrac,[1/2,3,23/8,13/11,22/7,-151/77])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[[0, 2], [3], [2, 1, 7], [1, 5, 2], [3, 7], [-2, 25, 1, 2]]</pre> |
<pre>[[0, 2], [3], [2, 1, 7], [1, 5, 2], [3, 7], [-2, 25, 1, 2]]</pre> |
||
Line 1,934: | Line 1,934: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
To do output one digit at a time, we first turn off buffering to be pedantic, then use a closure that yields one term per call. |
To do output one digit at a time, we first turn off buffering to be pedantic, then use a closure that yields one term per call. |
||
< |
<syntaxhighlight lang="perl">$|=1; |
||
sub rc2f { |
sub rc2f { |
||
Line 1,959: | Line 1,959: | ||
for ([14142,10000],[141421,100000],[1414214,1000000],[14142136,10000000]); |
for ([14142,10000],[141421,100000],[1414214,1000000],[14142136,10000000]); |
||
print "\n"; |
print "\n"; |
||
rcshow(rc2f(314285714,100000000));</ |
rcshow(rc2f(314285714,100000000));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,978: | Line 1,978: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">r2cf</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">num</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">denom</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">r2cf</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">num</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">denom</span><span style="color: #0000FF;">)</span> |
||
Line 2,015: | Line 2,015: | ||
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"for sqrt(2)"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sqrt2</span><span style="color: #0000FF;">)</span> |
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"for sqrt(2)"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sqrt2</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"for pi"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">)</span> |
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"for pi"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,046: | Line 2,046: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
< |
<syntaxhighlight lang="python">def r2cf(n1,n2): |
||
while n2: |
while n2: |
||
n1, (t1, n2) = n2, divmod(n1, n2) |
n1, (t1, n2) = n2, divmod(n1, n2) |
||
Line 2,059: | Line 2,059: | ||
print(list(r2cf(141421,100000))) # => [1, 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2] |
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(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]</ |
print(list(r2cf(14142136,10000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2]</syntaxhighlight> |
||
This version generates it from any real number (with rationals as a special case): |
This version generates it from any real number (with rationals as a special case): |
||
< |
<syntaxhighlight lang="python">def real2cf(x): |
||
while True: |
while True: |
||
t1, f = divmod(x, 1) |
t1, f = divmod(x, 1) |
||
Line 2,073: | Line 2,073: | ||
print(list(real2cf(Fraction(13, 11)))) # => [1, 5, 2] |
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]</ |
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]</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
<syntaxhighlight lang="quackery"> |
|||
<lang Quackery> |
|||
[ $ "bigrat.qky" loadfile ] now! |
[ $ "bigrat.qky" loadfile ] now! |
||
Line 2,110: | Line 2,110: | ||
dup echo |
dup echo |
||
say " = " |
say " = " |
||
cf echo cr ]</ |
cf echo cr ]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,135: | Line 2,135: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
Line 2,158: | Line 2,158: | ||
(real->cf (sqrt 2) 10) |
(real->cf (sqrt 2) 10) |
||
(real->cf pi 10) |
(real->cf pi 10) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 2,171: | Line 2,171: | ||
(formerly Perl 6) |
(formerly Perl 6) |
||
Straightforward implementation: |
Straightforward implementation: |
||
<lang |
<syntaxhighlight lang="raku" line>sub r2cf(Rat $x is copy) { |
||
gather loop { |
gather loop { |
||
$x -= take $x.floor; |
$x -= take $x.floor; |
||
Line 2,179: | Line 2,179: | ||
} |
} |
||
say r2cf(.Rat) for <1/2 3 23/8 13/11 22/7 1.41 1.4142136>;</ |
say r2cf(.Rat) for <1/2 3 23/8 13/11 22/7 1.41 1.4142136>;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>(0 2) |
<pre>(0 2) |
||
Line 2,189: | Line 2,189: | ||
(1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2)</pre> |
(1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2)</pre> |
||
As a silly one-liner: |
As a silly one-liner: |
||
<lang |
<syntaxhighlight lang="raku" line>sub r2cf(Rat $x is copy) { gather $x [R/]= 1 while ($x -= take $x.floor) > 0 }</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 2,198: | Line 2,198: | ||
* Checks were included to verify that the arguments being passed to '''r2cf''' are indeed numeric and also not zero. |
* Checks were included to verify that the arguments being passed to '''r2cf''' are indeed numeric and also not zero. |
||
* This REXX version also handles negative numbers. |
* This REXX version also handles negative numbers. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program converts a decimal or rational fraction to a continued fraction. */ |
||
numeric digits 230 /*determines how many terms to be gened*/ |
numeric digits 230 /*determines how many terms to be gened*/ |
||
say ' 1/2 ──► CF: ' r2cf( '1/2' ) |
say ' 1/2 ──► CF: ' r2cf( '1/2' ) |
||
Line 2,255: | Line 2,255: | ||
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ |
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ |
||
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ |
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ |
||
numeric digits d; return g/1</ |
numeric digits d; return g/1</syntaxhighlight> |
||
{{out|output|text= when using the default (internal) inputs:}} |
{{out|output|text= when using the default (internal) inputs:}} |
||
<pre> |
<pre> |
||
Line 2,281: | Line 2,281: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby"># Generate a continued fraction from a rational number |
||
def r2cf(n1,n2) |
def r2cf(n1,n2) |
||
Line 2,288: | Line 2,288: | ||
yield t1 |
yield t1 |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
===Testing=== |
===Testing=== |
||
'''Test 1:''' |
'''Test 1:''' |
||
< |
<syntaxhighlight lang="ruby">[[1,2], [3,1], [23,8], [13,11], [22,7], [-151,77]].each do |n1,n2| |
||
print "%10s : " % "#{n1} / #{n2}" |
print "%10s : " % "#{n1} / #{n2}" |
||
r2cf(n1,n2) {|n| print "#{n} "} |
r2cf(n1,n2) {|n| print "#{n} "} |
||
puts |
puts |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,307: | Line 2,307: | ||
'''Test 2:''' |
'''Test 2:''' |
||
<math>\sqrt 2</math> |
<math>\sqrt 2</math> |
||
< |
<syntaxhighlight lang="ruby">(5..8).each do |digit| |
||
n2 = 10 ** (digit-1) |
n2 = 10 ** (digit-1) |
||
n1 = (Math.sqrt(2) * n2).round |
n1 = (Math.sqrt(2) * n2).round |
||
Line 2,313: | Line 2,313: | ||
r2cf(n1,n2) {|n| print "#{n} "} |
r2cf(n1,n2) {|n| print "#{n} "} |
||
puts |
puts |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,322: | Line 2,322: | ||
</pre> |
</pre> |
||
'''Test 3:''' |
'''Test 3:''' |
||
< |
<syntaxhighlight lang="ruby">a =[ [31,10], |
||
[314,100], |
[314,100], |
||
[3142,1000], |
[3142,1000], |
||
Line 2,335: | Line 2,335: | ||
r2cf(n1,n2) {|n| print "#{n} "} |
r2cf(n1,n2) {|n| print "#{n} "} |
||
puts |
puts |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,349: | Line 2,349: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust"> |
||
struct R2cf { |
struct R2cf { |
||
n1: i64, |
n1: i64, |
||
Line 2,404: | Line 2,404: | ||
printcf!(314_285_714, 100_000_000); |
printcf!(314_285_714, 100_000_000); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 2,430: | Line 2,430: | ||
{{works with|Chez Scheme}} |
{{works with|Chez Scheme}} |
||
'''The Implementation''' |
'''The Implementation''' |
||
< |
<syntaxhighlight lang="scheme">; Create a terminating Continued Fraction generator for the given rational number. |
||
; Returns one term per call; returns #f when no more terms remaining. |
; Returns one term per call; returns #f when no more terms remaining. |
||
(define make-continued-fraction-gen |
(define make-continued-fraction-gen |
||
Line 2,466: | Line 2,466: | ||
(set! lst (append lst (list term))) |
(set! lst (append lst (list term))) |
||
(loop (cf)))) |
(loop (cf)))) |
||
lst)))</ |
lst)))</syntaxhighlight> |
||
'''The Task''' |
'''The Task''' |
||
<br /> |
<br /> |
||
Each continued fraction is displayed in both the conventional written form and as a list of terms. |
Each continued fraction is displayed in both the conventional written form and as a list of terms. |
||
< |
<syntaxhighlight lang="scheme">(printf "~%Basic examples:~%") |
||
(for-each |
(for-each |
||
(lambda (rat) |
(lambda (rat) |
||
Line 2,490: | Line 2,490: | ||
(printf "~a : ~a~%" rat (rat->cf-list rat))) |
(printf "~a : ~a~%" rat (rat->cf-list rat))) |
||
'(31/10 314/100 3142/1000 31428/10000 314285/100000 3142857/1000000 |
'(31/10 314/100 3142/1000 31428/10000 314285/100000 3142857/1000000 |
||
31428571/10000000 314285714/100000000 31415926535898/10000000000000))</ |
31428571/10000000 314285714/100000000 31415926535898/10000000000000))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,544: | Line 2,544: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
{{trans|Perl}} |
{{trans|Perl}} |
||
< |
<syntaxhighlight lang="ruby">func r2cf(num, den) { |
||
func() { |
func() { |
||
den || return nil |
den || return nil |
||
Line 2,568: | Line 2,568: | ||
seq.each { |r| showcf(r2cf(r.nude)) } |
seq.each { |r| showcf(r2cf(r.nude)) } |
||
print "\n" |
print "\n" |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,590: | Line 2,590: | ||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
===Direct translation=== |
===Direct translation=== |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.6 |
||
proc r2cf {n1 {n2 1}} { |
proc r2cf {n1 {n2 1}} { |
||
Line 2,608: | Line 2,608: | ||
return -code break |
return -code break |
||
}} $n1 $n2 |
}} $n1 $n2 |
||
}</ |
}</syntaxhighlight> |
||
Demonstrating: |
Demonstrating: |
||
< |
<syntaxhighlight lang="tcl">proc printcf {name cf} { |
||
puts -nonewline "$name -> " |
puts -nonewline "$name -> " |
||
while 1 { |
while 1 { |
||
Line 2,640: | Line 2,640: | ||
} { |
} { |
||
printcf "\[$n1;$n2\]" [r2cf $n1 $n2] |
printcf "\[$n1;$n2\]" [r2cf $n1 $n2] |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,664: | Line 2,664: | ||
</pre> |
</pre> |
||
===Objectified version=== |
===Objectified version=== |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.6 |
||
# General generator class based on coroutines |
# General generator class based on coroutines |
||
Line 2,772: | Line 2,772: | ||
# Demonstrate parsing of input in forms other than a direct pair of decimals |
# Demonstrate parsing of input in forms other than a direct pair of decimals |
||
printcf "1.5" [R2CF new 1.5] |
printcf "1.5" [R2CF new 1.5] |
||
printcf "23/7" [R2CF new 23/7]</ |
printcf "23/7" [R2CF new 23/7]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,801: | Line 2,801: | ||
{{libheader|Wren-rat}} |
{{libheader|Wren-rat}} |
||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/rat" for Rat |
||
import "/fmt" for Fmt |
import "/fmt" for Fmt |
||
Line 2,840: | Line 2,840: | ||
System.print() |
System.print() |
||
i = i + 1 |
i = i + 1 |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,870: | Line 2,870: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; |
||
real Val; |
real Val; |
||
Line 2,894: | Line 2,894: | ||
RlOut(0, Val); CrLf(0); |
RlOut(0, Val); CrLf(0); |
||
I:= I+2]; |
I:= I+2]; |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,908: | Line 2,908: | ||
Light weight, explicit state: |
Light weight, explicit state: |
||
< |
<syntaxhighlight lang="zkl">fcn r2cf(nom,dnom){ // -->Walker (iterator) |
||
Walker.tweak(fcn(state){ |
Walker.tweak(fcn(state){ |
||
nom,dnom:=state; |
nom,dnom:=state; |
||
Line 2,916: | Line 2,916: | ||
n |
n |
||
}.fp(List(nom,dnom))) // partial application (light weight closure) |
}.fp(List(nom,dnom))) // partial application (light weight closure) |
||
}</ |
}</syntaxhighlight> |
||
Heavy weight, implicit state: |
Heavy weight, implicit state: |
||
< |
<syntaxhighlight lang="zkl">fcn r2cf2(nom,dnom){ // -->Generator (heavy weight Walker) |
||
Utils.Generator(fcn(nom,dnom){ |
Utils.Generator(fcn(nom,dnom){ |
||
while(dnom){ |
while(dnom){ |
||
Line 2,926: | Line 2,926: | ||
Void.Stop; |
Void.Stop; |
||
},nom,dnom) |
},nom,dnom) |
||
}</ |
}</syntaxhighlight> |
||
Both of the above return an iterator so they function the same: |
Both of the above return an iterator so they function the same: |
||
< |
<syntaxhighlight lang="zkl">foreach nom,dnom in (T(T(1,2), T(3,1), T(23,8), T(13,11), T(22,7), |
||
T(14142,10000), T(141421,100000), T(1414214,1000000), |
T(14142,10000), T(141421,100000), T(1414214,1000000), |
||
T(14142136,10000000))){ |
T(14142136,10000000))){ |
||
r2cf(nom,dnom).walk(25).println(); // print up to 25 numbers |
r2cf(nom,dnom).walk(25).println(); // print up to 25 numbers |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |