Module:Rational: Difference between revisions
m abs() implemented |
m Minor optimisations for addition |
||
Line 140: | Line 140: | ||
return { inf = true, sign = b.sign } | return { inf = true, sign = b.sign } | ||
end | end | ||
-- regular case: both not NaN, not infinities | -- special case: one is zero | ||
if a.zero then | |||
return p.copy(b) | |||
end | |||
if b.zero then | |||
return p.copy(a) | |||
end | |||
-- regular case: both not NaN, not infinities, not zeros | |||
local gcd = { sign = 1 } | |||
for factor, power in pairs(a) do | |||
if type(factor) == 'number' then | |||
if math.min(power, b[factor] or 0) > 0 then | |||
gcd[factor] = math.min(power, b[factor]) | |||
end | |||
if math.max(power, b[factor] or 0) < 0 then | |||
gcd[factor] = math.max(power, b[factor]) | |||
end | |||
end | |||
end | |||
local a = p.div(a, gcd) | |||
local b = p.div(b, gcd) | |||
n_a, m_a = p.as_pair(a) | n_a, m_a = p.as_pair(a) | ||
Line 148: | Line 168: | ||
m = m_a * m_b | m = m_a * m_b | ||
return p.new(n, m) | return p.mul(p.new(n, m), gcd) | ||
end | end | ||