Convert decimal number to rational: Difference between revisions
Content added Content deleted
(add RPL) |
|||
Line 2,753: | Line 2,753: | ||
0.000001000001 = 1000001/1000000000000 ok</pre> |
0.000001000001 = 1000001/1000000000000 ok</pre> |
||
=={{header|RPL}}== |
|||
From HP-48 versions, conversion can be directly acheived with the <code>→Q</code> instruction. HP- models shall use instaed the following code, which is based on continuous fractions. |
|||
{{works with|Halcyon Calc|4.2.8}} |
|||
{| class="wikitable" |
|||
! RPL code |
|||
! Comment |
|||
|- |
|||
| |
|||
≪ |
|||
ABS LAST SIGN 1E6 → sign dmax |
|||
≪ (0,1) (1,0) |
|||
'''DO''' |
|||
SWAP OVER 4 ROLL INV IP |
|||
LAST FP 5 ROLLD |
|||
* + |
|||
'''UNTIL''' DUP2 IM SWAP IM * dmax > |
|||
4 PICK dmax INV < OR '''END''' |
|||
ROT ROT DROP2 |
|||
"'" OVER RE sign * →STR + "/" + |
|||
SWAP IM →STR + STR→ |
|||
≫ ≫ '<span style="color:blue">'''→PQ'''</span>' STO'' STO |
|||
| |
|||
<span style="color:blue">'''→PQ'''</span> ''( x → 'p/q' ) '' |
|||
store sign(x) and max denominator |
|||
a(0) = x ; hk(-2) = (0,1) ; hk(-1) = (1,0) |
|||
loop |
|||
reorder int(a(n)), hk(n-1) and hk(n-2) in stack |
|||
a(n+1)=1/frac(a(n)) back to top of stack |
|||
hk(n) = a(n)*hk(n-1) + hk(n-2) |
|||
until k(n)*(kn-1) > max denominator or |
|||
a(n+1) > max denominator |
|||
clean stack |
|||
convert a(n) from (p,q) to 'p/q' format |
|||
return 'p/q' |
|||
|} |
|||
.905405405405 <span style="color:blue">'''→PQ'''</span> |
|||
-3.875 <span style="color:blue">'''→PQ'''</span> |
|||
'''Output:''' |
|||
<span style="color:grey"> 2:</span> '67/74' |
|||
<span style="color:grey"> 1:</span> '-31/8' |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
{{works with|Ruby|1.9+}} |
{{works with|Ruby|1.9+}} |