Convert decimal number to rational: Difference between revisions

→‎{{header|JavaScript}}: Tidied, updated output.
(→‎{{header|JavaScript}}: Tidied, updated output.)
Line 1,409:
Deriving an approximation within a specified tolerance:
<syntaxhighlight lang="javascript">(() => {
'"use strict'";
 
// GENERIC FUNCTIONS ------------------ APPROXIMATE RATIO ----------------
 
// approxRatio :: Real -> Real -> Ratio
const approxRatio = epsepsilon => n => {
constn => {
const
c = gcdApprox(
0 < epsilon
? epsilon
const _gcd = (a, b) => (b < e ? a : _gcd(b,1 a/ % b)10000);
)(1, n);
 
return Ratio(
Math.floor(n / c), // numerator
Math.floor(1 / c) // denominator
);
};
 
 
// gcdApprox :: Real -> (Real, Real) -> Real
const gcdApprox = epsilon =>
const map = (fx, xsy) => xs.map(f);{
const _gcd = (a, b) =>
map( // Using a toleranceb < epsilon of 1/10000
? a
return : _gcd(Math.abs(x)b, Math.abs(y)a % b);
 
return _gcd(Math.abs(x), Math.abs(y));
};
 
 
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () =>
showJSON(// Using a tolerance of 1/10000
[0.9054054, 0.518518, 0.75]
map( // Using a tolerance epsilon of 1/10000
.map(
n => showRatio(approxRatio(0.0001)(n)),
[0.9054054, 0.518518, 0.75]compose(
showRatio,
n => showRatio(approxRatio(0.0001)(n)),
)
);
.join("\n");
 
// Epsilon -> Real -> Ratio
 
// ---------------- GENERIC FUNCTIONS ----------------
// approxRatio :: Real -> Real -> Ratio
 
const approxRatio = eps => n => {
// mapcompose (<<<) :: (b -> c) -> (a -> b) -> [a] -> [b]c
const
const gcdecompose = (e, x, y...fs) => {
// 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));
},fs.reduce(
c(f, = gcde(Boolean(epsg) ?=> epsx :=> f(1 / 10000g(x)), 1, n);
return Ratio( x => x
Math.floor(n / c), // numerator
Math.floor(1 / c) // denominator
);
};
 
// GENERIC FUNCTIONS ----------------------------------
 
// Ratio :: Int -> Int -> Ratio
const Ratio = (n, d) => ({
type: '"Ratio'",
'n': n, // numerator
'd': d // denominator
});
 
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
 
// showJSON :: a -> String
const showJSON = x => JSON.stringify(x, null, 2);
 
// showRatio :: Ratio -> String
const showRatio = nd =>
`${nd.n.toString() + '}/' + ${nd.d.toString()}`;
 
 
// MAIN ---
Line 1,458 ⟶ 1,485:
})();</syntaxhighlight>
{{Out}}
<pre>[67/74
"14/27",
"67/74",
]3/4</pre>
"14/27",
"3/4"
]</pre>
 
=={{header|jq}}==
9,655

edits