Convert decimal number to rational: Difference between revisions
Convert decimal number to rational (view source)
Revision as of 10:10, 21 September 2023
, 8 months ago→{{header|JavaScript}}: Tidied, updated output.
(→{{header|JavaScript}}: Tidied, updated output.) |
|||
Line 1,409:
Deriving an approximation within a specified tolerance:
<syntaxhighlight lang="javascript">(() => {
// approxRatio :: Real -> Real -> Ratio▼
const
c = gcdApprox(
0 < epsilon
? epsilon
)(1, n);
return Ratio(
);
};▼
// gcdApprox :: Real -> (Real, Real) -> Real
const gcdApprox = epsilon =>
const _gcd = (a, b) =>
? a
return _gcd(Math.abs(x), Math.abs(y));
};
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () =>
[0.9054054, 0.518518, 0.75]
▲ map( // Using a tolerance epsilon of 1/10000
.map(
n => showRatio(approxRatio(0.0001)(n)),▼
showRatio,
)
)
.join("\n");
// ---------------- GENERIC FUNCTIONS ----------------
▲ // approxRatio :: Real -> Real -> Ratio
▲ const approxRatio = eps => n => {
▲ const
const
// A function defined by the right-to-left
▲ const _gcd = (a, b) => (b < e ? a : _gcd(b, a % b));
// composition of all the functions in fs.
▲ return _gcd(Math.abs(x), Math.abs(y));
▲ Math.floor(n / c), // numerator
▲ Math.floor(1 / c) // denominator
);
▲ };
▲ // GENERIC FUNCTIONS ----------------------------------
// Ratio :: Int -> Int -> Ratio
const Ratio = (n, d) => ({
type:
});
▲ // map :: (a -> b) -> [a] -> [b]
▲ const map = (f, xs) => xs.map(f);
// showRatio :: Ratio -> String
const showRatio = nd =>
`${nd.n.toString()
// MAIN ---
Line 1,458 ⟶ 1,485:
})();</syntaxhighlight>
{{Out}}
<pre>
▲ "14/27",
▲]</pre>
=={{header|jq}}==
|