Convert decimal number to rational: Difference between revisions
Content added Content deleted
(→{{header|JavaScript}}: Tidied, updated output.) |
|||
Line 1,409: | Line 1,409: | ||
Deriving an approximation within a specified tolerance: |
Deriving an approximation within a specified tolerance: |
||
<syntaxhighlight lang="javascript">(() => { |
<syntaxhighlight lang="javascript">(() => { |
||
"use strict"; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
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 = () => |
const main = () => |
||
// Using a tolerance of 1/10000 |
|||
[0.9054054, 0.518518, 0.75] |
|||
⚫ | |||
.map( |
|||
⚫ | |||
compose( |
|||
showRatio, |
|||
⚫ | |||
) |
) |
||
) |
) |
||
.join("\n"); |
|||
// Epsilon -> Real -> Ratio |
|||
// ---------------- GENERIC FUNCTIONS ---------------- |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
const compose = (...fs) => |
|||
// A function defined by the right-to-left |
|||
⚫ | |||
// composition of all the functions in fs. |
|||
⚫ | |||
fs.reduce( |
|||
(f, g) => x => f(g(x)), |
|||
x => x |
|||
⚫ | |||
⚫ | |||
); |
); |
||
⚫ | |||
⚫ | |||
// Ratio :: Int -> Int -> Ratio |
// Ratio :: Int -> Int -> Ratio |
||
const Ratio = (n, d) => ({ |
const Ratio = (n, d) => ({ |
||
type: |
type: "Ratio", |
||
n, |
|||
d |
|||
}); |
}); |
||
⚫ | |||
⚫ | |||
// showJSON :: a -> String |
|||
const showJSON = x => JSON.stringify(x, null, 2); |
|||
// showRatio :: Ratio -> String |
// showRatio :: Ratio -> String |
||
const showRatio = nd => |
const showRatio = nd => |
||
nd.n.toString() |
`${nd.n.toString()}/${nd.d.toString()}`; |
||
// MAIN --- |
// MAIN --- |
||
Line 1,458: | Line 1,485: | ||
})();</syntaxhighlight> |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> |
<pre>67/74 |
||
⚫ | |||
"67/74", |
|||
⚫ | |||
⚫ | |||
"3/4" |
|||
⚫ | |||
=={{header|jq}}== |
=={{header|jq}}== |