How to resolve the algorithm Convert decimal number to rational step by step in the Bracmat programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Convert decimal number to rational step by step in the Bracmat programming language
Table of Contents
Problem Statement
The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: Acceptable output: Finite decimals are of course no problem:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Convert decimal number to rational step by step in the Bracmat programming language
Source code in the bracmat programming language
( ( exact
= integerPart decimalPart z
. @(!arg:?integerPart "." ?decimalPart)
& !integerPart
+ ( @( !decimalPart
: (? ((%@:~0) ?:?decimalPart)) [?z
)
& !decimalPart*10^(-1*!z)
| 0
)
| !arg
)
& ( approximation
= integerPart firstDecimals repeatingDecimals
, x y z z-y x-y numerator denominator
. @( !arg
: ?integerPart
"."
[?x
?firstDecimals
?repeatingDecimals
[?y
!repeatingDecimals
[?z
)
& !z+-1*!y:?z-y
& !x+-1*!y:?x-y
& 10:?numerator:?denominator
& ( !z-y:0&0:?repeatingDecimals
| 9:?denominator
& whl
' ( !z+-1:>!y:?z
& !numerator*10:?numerator
& !denominator*10+9:?denominator
)
& @(!repeatingDecimals:? #?repeatingDecimals)
)
& ( @(!firstDecimals:? #?firstDecimals)
| 0:?firstDecimals
)
& !integerPart
+ !firstDecimals*10^(!x-y+!z-y)
+ !numerator*!denominator^-1*!repeatingDecimals*10^!x-y
)
& "0.9054054054"
"0.5185185185"
"0.75"
"0.905405400"
"0.1428571428"
"35.000"
"35.001"
"0.00000000001"
"0.000001000001"
"0.9"
"0.99"
"0.909"
"0.9090"
"0.90909"
: ?decs
& whl
' ( !decs:%?dec ?decs
& approximation$!dec:?approx
& out
$ ( !dec
"="
(exact$!dec:?precise)
( !approx:!precise&
| str$("(approx. " !approx ")")
)
)
)
);
You may also check:How to resolve the algorithm Jump anywhere step by step in the COBOL programming language
You may also check:How to resolve the algorithm Associative array/Creation step by step in the Gosu programming language
You may also check:How to resolve the algorithm Logical operations step by step in the Self programming language
You may also check:How to resolve the algorithm Sorting algorithms/Bubble sort step by step in the Wren programming language
You may also check:How to resolve the algorithm Determine if only one instance is running step by step in the Go programming language