Continued fraction/Arithmetic/Construct from rational number: Difference between revisions

m
→‎{{header|Phix}}: rewrote, floor()->trunc(), and improved output
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
m (→‎{{header|Phix}}: rewrote, floor()->trunc(), and improved output)
Line 1,633:
 
=={{header|Phix}}==
<lang Phix>function r2cf(sequenceatom fractionnum, denom)
{{trans|C}}
atom quot = 0
<lang Phix>function r2cf(sequence fraction)
if denominatordenom!=0 then
integer {numerator, denominator} = fraction
integer quotient quot = 0trunc(num/denom)
{num,denom} = {denom,num-quot*denom}
if denominator!=0 then
quotient = floor(numerator/denominator)
{numerator,denominator} = {denominator,mod(numerator,denominator)}
end if
return {quotientquot,{numeratornum,denominatordenom}}
end function
 
constant DENOMINATOR = 2
procedure test(string txt, sequence tests)
printf(1,"Running %s :\n",{txt})
sequence fraction
integer quotient
printf(1,"Running %s :",{txt})
for i=1 to length(tests) do
fractionatom {num,denom} = tests[i], quot
printf(1,"\nForstring Nsep = %d, D = %d :",fraction);"
printf(1,"%d/%d ==> [",{num,denom})
while fraction[DENOMINATOR]!=0 do
while {quotient,fraction} denom!=0 r2cf(fraction)do
printf(1{quot,"{num,denom}} %d= "r2cf(num,quotientdenom)
printf(1,"%d",quot)
if denom=0 then exit end if
printf(1,"%s",sep)
sep = ","
end while
printf(1,"]\n")
end for
printf(1,"\n\n")
end procedure
 
constant examples = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}},
sqrt2 = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}},
pi = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}}
{31428571,10000000}, {314285714,100000000}, {3141592653589793,1000000000000000}}
test("the examples",examples)
Line 1,670 ⟶ 1,671:
<pre>
Running the examples :
For N = 1, D/2 ==> 2 : [0 ;2]
For N = 3, D/1 ==> 1 : [3]
For N = 23, D/8 ==> 8 : [2 ;1 ,7]
For N = 13, D/11 ==> 11 : [1 ;5 ,2]
For N = 22, D/7 ==> 7 : [3 ;7]
For N = -151, D/77 ==> 77 : [-2 25 1 ;-1,-24,-1,-2]
 
Running for sqrt(2) :
For N = 14142, D/10000 ==> 10000 : [1 ;2 ,2 ,2 ,2 ,2 ,1 ,1 ,29]
For N = 141421, D/100000 ==> 100000 : [1 ;2 ,2 ,2 ,2 ,2 ,2 ,3 ,1 ,1 ,3 ,1 ,7 ,2]
For N = 1414214, D/1000000 ==> 1000000 : [1 ;2 ,2 ,2 ,2 ,2 ,2 ,2 ,3 ,6 ,1 ,2 ,1 ,12]
For N14142136/10000000 = 14142136, D => 10000000 : [1 ;2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,6 ,1 ,2 ,4 ,1 ,1 ,2]
 
Running for pi :
For N = 31, D/10 ==> 10 : [3 ;10]
For N = 314, D/100 ==> 100 : [3 ;7 ,7]
For N = 3142, D/1000 ==> 1000 : [3 ;7 ,23 ,1 ,2]
For N = 31428, D/10000 ==> 10000 : [3 ;7 ,357]
For N = 314285, D/100000 ==> 100000 : [3 ;7 ,2857]
For N = 3142857, D/1000000 ==> 1000000 : [3 ;7 ,142857]
For N = 31428571, D/10000000 ==> 10000000 : [3 ;7 ,476190 ,3]
For N = 314285714, D/100000000 ==> 100000000 : [3 ;7 ,7142857]
3141592653589793/1000000000000000 ==> [3;7,15,1,292,1,1,1,2,1,3,1,14,4,2,3,1,12,5,1,5,20,1,11,1,1,1,2]
</pre>
 
7,818

edits