Module:Rational: Difference between revisions

Plumtree (talk | contribs)
m signum() -> u.signum()
Plumtree (talk | contribs)
Ket notation added
Line 197: Line 197:
local n, m = p.as_pair(a)
local n, m = p.as_pair(a)
return n / m
return n / m
end
-- return a rational number in ket notation
-- NaN, infinity, zero values use special representations
function p.as_ket(a, frame)
if type(a) == 'number' then
a = p.new(a)
end
-- special case: NaN
if a.nan then
return 'NaN'
end
-- special case: infinity
if a.inf then
local sign = '+'
if a.sign < 0 then
sign = '-'
end
return sign .. '∞'
end
-- special case: zero
if a.zero then
return '0'
end
-- regular case: not NaN, not infinity, not zero
local s = ''
if a.sign < 0 then
s = s .. '-'
end
-- preparing the argument
local largest_prime = -1
for factor, power in pairs(a) do
if type(factor) == 'number' then
if factor > largest_prime then
largest_prime = factor
end
end
end
local template_arg = ''
for i = 2, largest_prime do
if u.is_prime(i) then
if i > 2 then template_arg = template_arg .. ' ' end
template_arg = template_arg .. (a[i] or 0)
end
end
s = s .. frame:expandTemplate{
title = 'Monzo',
args = {template_arg}
}
return s
end
-- a version of as_ket() that can be {{#invoke:}}d
function p.ket(frame)
local unparsed = frame.args[1] or '1'
-- rational form
local sign, n, _m, m = unparsed:match('(%-?)%s*(%d*)%s*(/%s*(%d*))')
if n == nil then
-- integer form
sign, n = unparsed:match('(%-?)%s*(%d*)')
if n == nil then
-- parsing failure
return '<span style="color:red;">Invalid rational number: ' .. unparsed .. '.</span>'
else
m = 1
n = tonumber(n)
if #sign > 0 then
n = -n
end
end
else
n = tonumber(n)
m = tonumber(m)
if #sign > 0 then
n = -n
end
end
a = p.new(n, m)
return p.as_ket(a, frame)
end
end


return p
return p