Continued fraction/Arithmetic/Construct from rational number: Difference between revisions
Content added Content deleted
m (→{{header|Ada}}) |
|||
Line 2,410: | Line 2,410: | ||
314285714 / 100000000 = 3 7 7142857 |
314285714 / 100000000 = 3 7 7142857 |
||
</pre> |
</pre> |
||
=={{header|m4}}== |
|||
Being able to do such things in m4, without much trouble, makes it very useful as a program-source preprocessor. There may be better macroprocessors, but having ''some'' version of m4 is standard for POSIX platforms. |
|||
<syntaxhighlight lang="m4">divert(-1) |
|||
# m4 is a recursive macro language with eager evaluation. Generally |
|||
# there is no tail-call optimization. I shall define r2cf in a natural |
|||
# way, rather than try to mimic call-by-reference or lazy evaluation. |
|||
define(`r2cf',`$1/$2 => [_$0($1,$2,`')]') |
|||
define(`_r2cf', |
|||
`ifelse(eval($2 != 0),1, |
|||
`$3eval($1 / $2)$0($2,eval($1 % $2),ifelse($3,,`; ',```,'' '))')') |
|||
divert`'dnl |
|||
dnl |
|||
r2cf(1, 2) |
|||
r2cf(3, 1) |
|||
r2cf(23, 8) |
|||
r2cf(13, 11) |
|||
r2cf(22, 7) |
|||
r2cf(-151, 77) |
|||
dnl |
|||
r2cf(14142, 10000) |
|||
r2cf(141421, 100000) |
|||
r2cf(1414214, 1000000) |
|||
r2cf(14142136, 10000000) |
|||
dnl |
|||
r2cf(31, 10) |
|||
r2cf(314, 100) |
|||
r2cf(3142, 1000) |
|||
r2cf(31428, 10000) |
|||
r2cf(314285, 100000) |
|||
r2cf(3142857, 1000000) |
|||
r2cf(31428571, 10000000) |
|||
r2cf(314285714, 100000000) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ m4 continued-fraction-from-rational.m4 |
|||
1/2 => [0; 2] |
|||
3/1 => [3] |
|||
23/8 => [2; 1, 7] |
|||
13/11 => [1; 5, 2] |
|||
22/7 => [3; 7] |
|||
-151/77 => [-1; -1, -24, -1, -2] |
|||
14142/10000 => [1; 2, 2, 2, 2, 2, 1, 1, 29] |
|||
141421/100000 => [1; 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2] |
|||
1414214/1000000 => [1; 2, 2, 2, 2, 2, 2, 2, 3, 6, 1, 2, 1, 12] |
|||
14142136/10000000 => [1; 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2] |
|||
31/10 => [3; 10] |
|||
314/100 => [3; 7, 7] |
|||
3142/1000 => [3; 7, 23, 1, 2] |
|||
31428/10000 => [3; 7, 357] |
|||
314285/100000 => [3; 7, 2857] |
|||
3142857/1000000 => [3; 7, 142857] |
|||
31428571/10000000 => [3; 7, 476190, 3] |
|||
314285714/100000000 => [3; 7, 7142857]</pre> |
|||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |