How to resolve the algorithm Convert decimal number to rational step by step in the jq 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 jq 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 jq programming language
Source code in the jq programming language
# include "rational"; # a reminder that r/2 and power/1 are required
# Input: any JSON number, not only a decimal
# Output: a rational, constructed using r/2
# Requires power/1 (to take advantage of gojq's support for integer arithmetic)
# and r/2 (for rational number constructor)
def number_to_r:
# input: a decimal string
# $in - either null or the original input
# $e - the integer exponent of the original number, or 0
def dtor($in; $e):
index(".") as $ix
| if $in and ($ix == null) then $in
else (if $ix then sub("[.]"; "") else . end | tonumber) as $n
| (if $ix then ((length - ($ix+1)) - $e) else - $e end) as $p
| if $p >= 0
then r( $n; 10|power($p))
else r( $n * (10|power(-$p)); 1)
end
end;
. as $in
| tostring
| if (test("[Ee]")|not) then dtor($in; 0)
else capture("^(?<s>[^eE]*)[Ee](?<e>.*$)")
| (.e | if length > 0 then tonumber else 0 end) as $e
| .s | dtor(null; $e)
end ;
0.9054054,
0.518518,
0.75,
1e308
| "\(.) → \(number_to_r | rpp)"
You may also check:How to resolve the algorithm Phrase reversals step by step in the Swift programming language
You may also check:How to resolve the algorithm Roots of unity step by step in the Scala programming language
You may also check:How to resolve the algorithm Amb step by step in the Python programming language
You may also check:How to resolve the algorithm Dot product step by step in the Maple programming language
You may also check:How to resolve the algorithm Roots of a quadratic function step by step in the OCaml programming language