Module:Simplified fraction: Difference between revisions

Tristanbay (talk | contribs)
Created reduced fraction module
 
Tristanbay (talk | contribs)
Undo revision 214299 by Tristanbay (talk)
Tag: Undo
 
(15 intermediate revisions by 2 users not shown)
Line 1: Line 1:
local p = {}
local p = {}
local rat = require("Module:Rational")


function p.refrac(frame)
local function simplify(n, d)
local num, denom = rat.as_pair(rat.new(frame.args["n"], frame.args["d"])) -- hopefully this reduces the numbers
local a = math.max(n, d)
local whole = frame.args["mixed"] and math.floor(num / denom) or 0
local b = math.min(n, d)
local frac = whole ~= 0 and string.format("{{frac|%d|%d|%d}}", whole, num - whole * denom, denom) or string.format("{{frac|%d|%d}}", num, denom)
local g = 1
return frame:preprocess(frac)
while b ~= 0 do
g = a % b
a = b
b = g
end
return math.floor(n / a), math.floor(d / a)
end
end
function p.simfrac(frame)
local n = frame.args["n"]
local d = frame.args["d"]
local mixed = frame.args["mixed"] == "true" and true or false
local num, denom = simplify(n, d)
local whole = mixed and math.floor(num / denom) or 0
local ft
if denom == 1 then
ft = string.format("%d", num)
elseif whole ~= 0 then
ft = string.format("%d %d⁄%d", whole, num - whole * denom, denom)
else
ft = string.format("%d⁄%d", num, denom)
end
return frame:preprocess(ft)
end
return p