Difference between revisions of "Module:Math"

From MINR.ORG WIKI
(Undid revision 586573269 by Mr. Stradivarius (talk) the code refactor broke some existing modules - revert for now while I work out the extent of the problem)
(Undid revision 586591521 by Mr. Stradivarius (talk) reinstate the new version - the problem was limited to two modules, which I will now fix)
Line 4: Line 4:
  
 
]]
 
]]
local z = {}
 
  
-- Generate random number
+
local yesno = require('Module:Yesno')
function z.random( frame )
+
local getArgs = require('Module:Arguments').getArgs
    first = tonumber(frame.args[1]) -- if it doesn't exist it's NaN, if not a number it's nil
 
    second = tonumber(frame.args[2])
 
  
    if first then -- if NaN or nil, will skip down to final return
+
local p = {} -- Holds functions to be returned from #invoke, and functions to make available to other Lua modules.
        if first <= second then -- could match if both nil, but already checked that first is a number in last line
+
local wrap = {} -- Holds wrapper functions that process arguments from #invoke. These act as intemediary between functions meant for #invoke and functions meant for Lua.
            return math.random(first, second)
+
 
        end
+
--[[
        return math.random(first)
+
Helper functions used to avoid redundant code.
    end 
+
]]
    return math.random()
+
 
 +
local function err(msg)
 +
-- Generates wikitext error messages.
 +
return mw.ustring.format('<strong class="error">Formatting error: %s</strong>', msg)
 +
end
 +
 
 +
local function unpackNumberArgs(args)
 +
-- Returns an unpacked list of arguments specified with numerical keys.
 +
local ret = {}
 +
for k, v in pairs(args) do
 +
if type(k) == 'number' then
 +
table.insert(ret, v)
 +
end
 +
end
 +
return unpack(ret)
 +
end
 +
 
 +
local function makeArgArray(...)
 +
-- Makes an array of arguments from a list of arguments that might include nils.
 +
local args = {...} -- Table of arguments. It might contain nils or non-number values, so we can't use ipairs.
 +
local nums = {} -- Stores the numbers of valid numerical arguments.
 +
local ret = {}
 +
for k, v in pairs(args) do
 +
v = p._cleanNumber(v)
 +
if v then
 +
nums[#nums + 1] = k
 +
args[k] = v
 +
end
 +
end
 +
table.sort(nums)
 +
for i, num in ipairs(nums) do
 +
ret[#ret + 1] = args[num]
 +
end
 +
return ret
 +
end
 +
 
 +
local function applyFuncToArgs(func, ...)
 +
-- Use a function on all supplied arguments, and return the result. The function must accept two numbers as parameters,
 +
-- and must return a number as an output. This number is then supplied as input to the next function call.
 +
local vals = makeArgArray(...)
 +
local count = #vals -- The number of valid arguments
 +
if count == 0 then return
 +
-- Exit if we have no valid args, otherwise removing the first arg would cause an error.
 +
nil, 0
 +
end
 +
local ret = table.remove(vals, 1)
 +
for _, val in ipairs(vals) do
 +
ret = func(ret, val)
 +
end
 +
return ret, count
 +
end
 +
 
 +
--[[
 +
random
 +
 
 +
Generate a random number
 +
 
 +
Usage:
 +
{{#invoke: Math | random }}
 +
{{#invoke: Math | random | maximum value }}
 +
{{#invoke: Math | random | minimum value | maximum value }}
 +
]]
 +
 
 +
function wrap.random(args)
 +
local first = p._cleanNumber(args[1])
 +
local second = p._cleanNumber(args[2])
 +
return p._random(first, second)
 +
end
 +
 
 +
function p._random(first, second)
 +
math.randomseed(mw.site.stats.edits + mw.site.stats.pages + os.time() + math.floor(os.clock() * 1000000000))
 +
-- math.random will throw an error if given an explicit nil parameter, so we need to use if statements to check the params.
 +
if first and second then
 +
if first <= second then -- math.random doesn't allow the first number to be greater than the second.
 +
return math.random(first, second)
 +
end
 +
elseif first then
 +
return math.random(first)
 +
else
 +
return math.random()
 +
end
 
end
 
end
  
Line 26: Line 103:
  
 
Usage:
 
Usage:
    {{#invoke: Math | order | value }}
+
{{#invoke: Math | order | value }}
 
]]
 
]]
function z.order(frame)
+
 
    local input_string = (frame.args[1] or frame.args.x or '0');
+
function wrap.order(args)
    local input_number;
+
local input_string = (args[1] or args.x or '0');
   
+
local input_number = p._cleanNumber(input_string);
    input_number = z._cleanNumber( frame, input_string );
+
if input_number == nil then
    if input_number == nil then
+
return err('order of magnitude input appears non-numeric')
        return '<strong class="error">Formatting error: Order of magnitude input appears non-numeric</strong>'
+
else
    else
+
return p._order(input_number)
        return z._order( input_number )
+
end     
    end     
 
 
end
 
end
function z._order(x)
+
 
    if x == 0 then return 0 end
+
function p._order(x)
    return math.floor(math.log10(math.abs(x)))
+
if x == 0 then return 0 end
 +
return math.floor(math.log10(math.abs(x)))
 
end
 
end
  
Line 50: Line 127:
  
 
Usage:
 
Usage:
    {{ #invoke: Math | precision | value }}
+
{{ #invoke: Math | precision | value }}
 
]]
 
]]
function z.precision( frame )
+
 
    local input_string = (frame.args[1] or frame.args.x or '0');
+
function wrap.precision(args)
    local trap_fraction = frame.args.check_fraction or false;
+
local input_string = (args[1] or args.x or '0');
    local input_number;
+
local trap_fraction = args.check_fraction;
   
+
local input_number;
    if type( trap_fraction ) == 'string' then
+
 
        trap_fraction = trap_fraction:lower();
+
if yesno(trap_fraction, true) then -- Returns true for all input except nil, false, "no", "n", "0" and a few others. See [[Module:Yesno]].
        if trap_fraction == 'false' or trap_fraction == '0' or
+
local pos = string.find(input_string, '/', 1, true);
                trap_fraction == 'no' or trap_fraction == '' then
+
if pos ~= nil then
            trap_fraction = false;
+
if string.find(input_string, '/', pos + 1, true) == nil then
        else
+
local denominator = string.sub(input_string, pos+1, -1);
            trap_fraction = true;
+
local denom_value = tonumber(denominator);
        end
+
if denom_value ~= nil then
    end
+
return math.log10(denom_value);
   
+
end
    if trap_fraction then
+
end                         
        local pos = string.find( input_string, '/', 1, true );
+
end
        if pos ~= nil then
+
end     
            if string.find( input_string, '/', pos + 1, true ) == nil then
+
 
                local denominator = string.sub( input_string, pos+1, -1 );
+
input_number, input_string = p._cleanNumber(input_string);
                local denom_value = tonumber( denominator );
+
if input_string == nil then
                if denom_value ~= nil then
+
return err('precision input appears non-numeric')
                    return math.log10(denom_value);
+
else
                end
+
return p._precision(input_string)
            end                         
+
end     
        end
 
    end     
 
   
 
    input_number, input_string = z._cleanNumber( frame, input_string );
 
    if input_string == nil then
 
        return '<strong class="error">Formatting error: Precision input appears non-numeric</strong>'
 
    else
 
        return z._precision( input_string )
 
    end     
 
 
end
 
end
function z._precision( x )   
 
    x = string.upper( x )
 
  
    local decimal = string.find( x, '.', 1, true )
+
function p._precision(x)
    local exponent_pos = string.find( x, 'E', 1, true )
+
if type(x) == 'number' then
    local result = 0;
+
x = tostring(x)
   
+
end
    if exponent_pos ~= nil then
+
x = string.upper(x)
        local exponent = string.sub( x, exponent_pos + 1 )
+
 
        x = string.sub( x, 1, exponent_pos - 1 )
+
local decimal = x:find('%.')
        result = result - tonumber( exponent )
+
local exponent_pos = x:find('E')
    end     
+
local result = 0;
   
+
 
    if decimal ~= nil then
+
if exponent_pos ~= nil then
        result = result + string.len( x ) - decimal
+
local exponent = string.sub(x, exponent_pos + 1)
        return result
+
x = string.sub(x, 1, exponent_pos - 1)
    end
+
result = result - tonumber(exponent)
       
+
end     
    local pos = string.len( x );
+
 
    while x:byte(pos) == string.byte('0') do
+
if decimal ~= nil then
        pos = pos - 1
+
result = result + string.len(x) - decimal
        result = result - 1
+
return result
        if pos <= 0 then
+
end
            return 0
+
 
        end
+
local pos = string.len(x);
    end
+
while x:byte(pos) == string.byte('0') do
   
+
pos = pos - 1
    return result
+
result = result - 1
 +
if pos <= 0 then
 +
return 0
 +
end
 +
end
 +
 
 +
return result
 
end
 
end
  
Line 123: Line 195:
  
 
Usage:
 
Usage:
    {{#invoke:Math| max | value1 | value2 | ... }}
+
{{#invoke:Math| max | value1 | value2 | ... }}
OR
 
    {{#invoke:Math| max }}
 
  
When used with no arguments, it takes its input from the parent
+
Note, any values that do not evaluate to numbers are ignored.
frame.  Note, any values that do not evaluate to numbers are ignored.
 
 
]]
 
]]
function z.max( frame )
+
 
    local args = frame.args;
+
function wrap.max(args)
   
+
return p._max(unpackNumberArgs(args))
    if args[1] == nil then
+
end
        local parent = frame:getParent();
+
 
        args = parent.args;
+
function p._max(...)
    end
+
local function maxOfTwo(a, b)
    local max_value = nil;
+
if a > b then
   
+
return a
    local i = 1;
+
else
    while args[i] ~= nil do
+
return b
        local val = z._cleanNumber( frame, args[i] );
+
end
        if val ~= nil then
+
end
            if max_value == nil or val > max_value then
+
local max_value = applyFuncToArgs(maxOfTwo, ...)
                max_value = val;
+
if max_value then
            end
+
return max_value
        end      
+
end
        i = i + 1;
 
    end
 
 
 
    return max_value
 
 
end
 
end
  
Line 159: Line 224:
  
 
Usage:
 
Usage:
    {{#invoke:Math| min | value1 | value2 | ... }}
+
{{#invoke:Math| min | value1 | value2 | ... }}
 
OR
 
OR
    {{#invoke:Math| min }}
+
{{#invoke:Math| min }}
  
 
When used with no arguments, it takes its input from the parent
 
When used with no arguments, it takes its input from the parent
 
frame.  Note, any values that do not evaluate to numbers are ignored.
 
frame.  Note, any values that do not evaluate to numbers are ignored.
 
]]
 
]]
function z.min( frame )
+
 
    local args = frame.args;
+
function wrap.min(args)
   
+
return p._min(unpackNumberArgs(args))
    if args[1] == nil then
+
end
        local parent = frame:getParent();
+
 
        args = parent.args;
+
function p._min(...)
    end
+
local function minOfTwo(a, b)
    local min_value = nil;
+
if a < b then
   
+
return a
    local i = 1;
+
else
    while args[i] ~= nil do
+
return b
        local val = z._cleanNumber( frame, args[i] );
+
end
        if val ~= nil then
+
end
            if min_value == nil or val < min_value then
+
local min_value = applyFuncToArgs(minOfTwo, ...)
                min_value = val;
+
if min_value then
            end
+
return min_value
        end      
+
end
        i = i + 1;
 
    end
 
 
 
    return min_value
 
 
end
 
end
  
 
--[[
 
--[[
 
average  
 
average  
+
 
 
Finds the average
 
Finds the average
+
 
 
Usage:
 
Usage:
    {{#invoke:Math| average | value1 | value2 | ... }}
+
{{#invoke:Math| average | value1 | value2 | ... }}
 
OR
 
OR
    {{#invoke:Math| average }}
+
{{#invoke:Math| average }}
+
 
When used with no arguments, it takes its input from the parent
+
Note, any values that do not evaluate to numbers are ignored.
frame.  Note, any values that do not evaluate to numbers are ignored.
 
 
]]
 
]]
function z.average( frame )
+
 
    local args = frame.args;
+
function wrap.average(args)
    if args[1] == nil then
+
return p._average(unpackNumberArgs(args))
        local parent = frame:getParent();
+
end
        args = parent.args;
+
 
    end
+
function p._average(...)
    local sum = 0;
+
local function getSum(a, b)
    local count = 0;
+
return a + b
+
end
    local i = 1;
+
local sum, count = applyFuncToArgs(getSum, ...)
    while args[i] ~= nil do
+
if not sum then
        local val = z._cleanNumber( frame, args[i] );
+
return 0
        if val ~= nil then
+
else
            sum = sum + val
+
return sum / count
            count = count + 1
+
end
        end       
 
        i = i + 1;
 
    end
 
 
    return (count == 0 and 0 or sum/count)
 
 
end
 
end
  
Line 230: Line 285:
  
 
Usage:
 
Usage:
    {{#invoke:Math | round | value | precision }}
+
{{#invoke:Math | round | value | precision }}
   
+
 
 +
--]]
 +
 
 +
function wrap.round(args)
 +
local value = p._cleanNumber(args[1] or args.value or 0)
 +
local precision = p._cleanNumber(args[2] or args.precision or 0)
 +
if value == nil or precision == nil then
 +
return err('round input appears non-numeric')
 +
else
 +
return p._round(value, precision)
 +
end   
 +
end
 +
 
 +
function p._round(value, precision)
 +
local rescale = math.pow(10, precision or 0);
 +
return math.floor(value * rescale + 0.5) / rescale;
 +
end
 +
 
 +
--[[
 +
mod
 +
 
 +
Implements the modulo operator
 +
 
 +
Usage:
 +
{{#invoke:Math | mod | x | y }}
 +
 
 +
--]]
 +
 
 +
function wrap.mod(args)
 +
local x = p._cleanNumber(args[1])
 +
local y = p._cleanNumber(args[2])
 +
if not x then
 +
return err('first argument to mod appears non-numeric')
 +
elseif not y then
 +
return err('second argument to mod appears non-numeric')
 +
else
 +
return p._mod(x, y)
 +
end   
 +
end
 +
 
 +
function p._mod(x, y)
 +
local ret = x % y
 +
if not (0 <= ret and ret < y) then
 +
ret = 0
 +
end
 +
return ret
 +
end
 +
 
 +
--[[
 +
gcd
 +
 
 +
Calculates the greatest common divisor of multiple numbers
 +
 
 +
Usage:
 +
{{#invoke:Math | gcd | value 1 | value 2 | value 3 | ... }}
 
--]]
 
--]]
function z.round(frame)
+
 
    local value, precision;
+
function wrap.gcd(args)
   
+
return p._gcd(unpackNumberArgs(args))
    value = z._cleanNumber( frame, frame.args[1] or frame.args.value or 0 );
 
    precision = z._cleanNumber( frame, frame.args[2] or frame.args.precision or 0 );
 
   
 
    if value == nil or precision == nil then
 
        return '<strong class="error">Formatting error: Round input appears non-numeric</strong>'
 
    else
 
        return z._round( value, precision );
 
    end   
 
 
end
 
end
function z._round( value, precision )
+
 
    local rescale = math.pow( 10, precision );
+
function p._gcd(...)
    return math.floor( value * rescale + 0.5 ) / rescale;
+
local function findGcd(a, b)
 +
local r = b
 +
local oldr = a
 +
while r ~= 0 do
 +
local quotient = math.floor(oldr / r)
 +
oldr, r = r, oldr - quotient * r
 +
end
 +
if oldr < 0 then
 +
oldr = oldr * -1
 +
end
 +
return oldr
 +
end
 +
local result, count = applyFuncToArgs(findGcd, ...)
 +
return result
 
end
 
end
  
Line 257: Line 371:
  
 
Usage:
 
Usage:
    {{#invoke: Math | precision_format | number | precision }}
+
{{#invoke: Math | precision_format | number | precision }}
 
]]
 
]]
function z.precision_format( frame )
 
    -- For access to Mediawiki built-in formatter.
 
    local lang = mw.getContentLanguage();
 
   
 
    local value_string, value, precision;
 
    value, value_string = z._cleanNumber( frame, frame.args[1] or 0 );
 
    precision = z._cleanNumber( frame, frame.args[2] or 0 );
 
   
 
    -- Check for non-numeric input
 
    if value == nil or precision == nil then
 
        return '<strong class="error">Formatting error: invalid input when rounding</strong>'
 
    end
 
   
 
    local current_precision = z._precision( value );
 
  
    local order = z._order( value );
+
function wrap.precision_format(args)
   
+
local value_string = args[1] or 0
    -- Due to round-off effects it is neccesary to limit the returned precision under
+
local precision = args[2] or 0
    -- some circumstances because the terminal digits will be inaccurately reported.
+
return p._precision_format(value_string, precision)
    if order + precision >= 14 then
+
end
        orig_precision = z._precision( value_string );
+
 
        if order + orig_precision >= 14 then
+
function p._precision_format(value_string, precision)
            precision = 13 - order;         
+
-- For access to Mediawiki built-in formatter.
        end         
+
local lang = mw.getContentLanguage();
    end
+
 
 +
local value
 +
value, value_string = p._cleanNumber(value_string)
 +
precision = p._cleanNumber(precision)
 +
 
 +
-- Check for non-numeric input
 +
if value == nil or precision == nil then
 +
return err('invalid input when rounding')
 +
end
 +
 
 +
local current_precision = p._precision(value)
 +
local order = p._order(value)
 +
 
 +
-- Due to round-off effects it is neccesary to limit the returned precision under
 +
-- some circumstances because the terminal digits will be inaccurately reported.
 +
if order + precision >= 14 then
 +
orig_precision = p._precision(value_string)
 +
if order + orig_precision >= 14 then
 +
precision = 13 - order;         
 +
end         
 +
end
 +
 
 +
-- If rounding off, truncate extra digits
 +
if precision < current_precision then
 +
value = p._round(value, precision)
 +
current_precision = p._precision(value)
 +
end   
 +
 
 +
local formatted_num = lang:formatNum(math.abs(value))
 +
local sign
 +
 
 +
-- Use proper unary minus sign rather than ASCII default
 +
if value < 0 then
 +
sign = '−'
 +
else
 +
sign = ''
 +
end   
 +
 
 +
-- Handle cases requiring scientific notation
 +
if string.find(formatted_num, 'E', 1, true) ~= nil or math.abs(order) >= 9 then
 +
value = value * math.pow(10, -order)
 +
current_precision = current_precision + order
 +
precision = precision + order
 +
formatted_num = lang:formatNum(math.abs(value))
 +
else
 +
order = 0;       
 +
end
 +
formatted_num = sign .. formatted_num
  
    -- If rounding off, truncate extra digits
+
-- Pad with zeros, if needed     
    if precision < current_precision then
+
if current_precision < precision then
        value = z._round( value, precision );
+
local padding
        current_precision = z._precision( value );
+
if current_precision <= 0 then
    end   
+
if precision > 0 then
   
+
local zero_sep = lang:formatNum(1.1)
    local formatted_num = lang:formatNum( math.abs(value) );
+
formatted_num = formatted_num .. zero_sep:sub(2,2)
    local sign;
 
   
 
    -- Use proper unary minus sign rather than ASCII default
 
    if value < 0 then
 
        sign = '−';
 
    else
 
        sign = '';
 
    end   
 
       
 
    -- Handle cases requiring scientific notation
 
    if string.find( formatted_num, 'E', 1, true ) ~= nil or math.abs(order) >= 9 then
 
        value = value * math.pow( 10, -order );
 
        current_precision = current_precision + order;
 
        precision = precision + order;
 
        formatted_num = lang:formatNum( math.abs(value) );
 
    else
 
        order = 0;       
 
    end
 
    formatted_num = sign .. formatted_num;
 
   
 
    -- Pad with zeros, if needed     
 
    if current_precision < precision then
 
        local padding;
 
        if current_precision <= 0 then
 
            if precision > 0 then
 
                local zero_sep = lang:formatNum( 1.1 );
 
                formatted_num = formatted_num .. zero_sep:sub(2,2);
 
  
                padding = precision;
+
padding = precision
                if padding > 20 then
+
if padding > 20 then
                    padding = 20;
+
padding = 20
                end
+
end
               
 
                formatted_num = formatted_num .. string.rep( '0', padding );
 
            end           
 
        else                 
 
            padding = precision - current_precision
 
            if padding > 20 then
 
                padding = 20;
 
            end
 
            formatted_num = formatted_num .. string.rep( '0', padding );
 
        end
 
    end
 
  
    -- Add exponential notation, if necessary.
+
formatted_num = formatted_num .. string.rep('0', padding)
    if order ~= 0 then
+
end           
        -- Use proper unary minus sign rather than ASCII default
+
else                 
        if order < 0 then
+
padding = precision - current_precision
            order = '−' .. lang:formatNum( math.abs(order) );
+
if padding > 20 then
        else
+
padding = 20
            order = lang:formatNum( order );
+
end
        end     
+
formatted_num = formatted_num .. string.rep('0', padding)
       
+
end
        formatted_num = formatted_num .. '<span style="margin:0 .15em 0 .25em">×</span>10<sup>' .. order .. '</sup>'
+
end
    end
+
 
   
+
-- Add exponential notation, if necessary.
    return formatted_num;
+
if order ~= 0 then
 +
-- Use proper unary minus sign rather than ASCII default
 +
if order < 0 then
 +
order = '−' .. lang:formatNum(math.abs(order))
 +
else
 +
order = lang:formatNum(order)
 +
end     
 +
 
 +
formatted_num = formatted_num .. '<span style="margin:0 .15em 0 .25em">×</span>10<sup>' .. order .. '</sup>'
 +
end
 +
 
 +
return formatted_num
 
end
 
end
  
Line 357: Line 477:
 
]]
 
]]
  
function z._cleanNumber( frame, number_string )
+
function p._cleanNumber(number_string)
    if number_string == nil or number_string:len() == 0 then
+
if type(number_string) == 'number' then
        return nil, nil;
+
-- We were passed a number, so we don't need to do any processing.
    end  
+
return number_string, tostring(number_string)
   
+
elseif type(number_string) ~= 'string' or not number_string:find('%S') then
    -- Attempt basic conversion
+
-- We were passed a non-string or a blank string, so exit.
    local number = tonumber( number_string )
+
return nil, nil;
   
+
end
    -- If failed, attempt to evaluate input as an expression
+
 
    if number == nil then      
+
-- Attempt basic conversion
        local attempt = frame:preprocess( '{{#expr: ' .. number_string .. '}}' );
+
local number = tonumber(number_string)
        attempt = tonumber( attempt );
+
 
        if attempt ~= nil then
+
-- If failed, attempt to evaluate input as an expression
            number = attempt;
+
if number == nil then
            number_string = tostring( number );
+
local frame = mw.getCurrentFrame()
        else
+
local attempt = frame:preprocess('{{#expr: ' .. number_string .. '}}')
            number = nil;
+
attempt = tonumber(attempt)
            number_string = nil;
+
if attempt ~= nil then
        end
+
number = attempt
    else
+
number_string = tostring(number)
    -- String is valid but may contain padding, clean it.
+
else
        number_string = number_string:match( "^%s*(.-)%s*$" );
+
number = nil
    end
+
number_string = nil
   
+
end
    return number, number_string;
+
else
 +
number_string = number_string:match("^%s*(.-)%s*$") -- String is valid but may contain padding, clean it.
 +
number_string = number_string:match("^%+(.*)$") or number_string -- Trim any leading + signs.
 +
if number_string:find('^%-?0[xX]') then
 +
-- Number is using 0xnnn notation to indicate base 16; use the number that Lua detected instead.
 +
number_string = tostring(number)
 +
end
 +
end
 +
 
 +
return number, number_string
 +
end
 +
 
 +
--[[
 +
Wrapper function that does basic argument processing. This ensures that all functions from #invoke can use either the current
 +
frame or the parent frame, and it also trims whitespace for all arguments and removes blank arguments.
 +
]]
 +
 
 +
local function makeWrapper(funcName)
 +
return function (frame)
 +
local args = getArgs(frame) -- Argument processing is left to Module:Arguments. Whitespace is trimmed and blank arguments are removed.
 +
return wrap[funcName](args)
 +
end
 +
end
 +
 
 +
for funcName in pairs(wrap) do
 +
p[funcName] = makeWrapper(funcName)
 
end
 
end
  
return z
+
return p

Revision as of 06:49, 18 December 2013

Documentation for this module may be created at Module:Math/doc

--[[

This module provides a number of basic mathematical operations.

]]

local yesno = require('Module:Yesno')
local getArgs = require('Module:Arguments').getArgs

local p = {} -- Holds functions to be returned from #invoke, and functions to make available to other Lua modules.
local wrap = {} -- Holds wrapper functions that process arguments from #invoke. These act as intemediary between functions meant for #invoke and functions meant for Lua.

--[[
Helper functions used to avoid redundant code.
]]

local function err(msg)
	-- Generates wikitext error messages.
	return mw.ustring.format('<strong class="error">Formatting error: %s</strong>', msg)
end

local function unpackNumberArgs(args)
	-- Returns an unpacked list of arguments specified with numerical keys.
	local ret = {}
	for k, v in pairs(args) do
		if type(k) == 'number' then
			table.insert(ret, v)
		end
	end
	return unpack(ret)
end

local function makeArgArray(...)
	-- Makes an array of arguments from a list of arguments that might include nils.
	local args = {...} -- Table of arguments. It might contain nils or non-number values, so we can't use ipairs.
	local nums = {} -- Stores the numbers of valid numerical arguments.
	local ret = {}
	for k, v in pairs(args) do
		v = p._cleanNumber(v)
		if v then
			nums[#nums + 1] = k
			args[k] = v
		end
	end
	table.sort(nums)
	for i, num in ipairs(nums) do
		ret[#ret + 1] = args[num]
	end
	return ret
end

local function applyFuncToArgs(func, ...)
	-- Use a function on all supplied arguments, and return the result. The function must accept two numbers as parameters,
	-- and must return a number as an output. This number is then supplied as input to the next function call.
	local vals = makeArgArray(...)	
	local count = #vals -- The number of valid arguments
	if count == 0 then return
		-- Exit if we have no valid args, otherwise removing the first arg would cause an error.
		nil, 0
	end 
	local ret = table.remove(vals, 1)
	for _, val in ipairs(vals) do
		ret = func(ret, val)
	end
	return ret, count
end

--[[
random

Generate a random number

Usage:
{{#invoke: Math | random }}
{{#invoke: Math | random | maximum value }}
{{#invoke: Math | random | minimum value | maximum value }}
]]

function wrap.random(args)
	local first = p._cleanNumber(args[1])
	local second = p._cleanNumber(args[2])
	return p._random(first, second)
end

function p._random(first, second)
	math.randomseed(mw.site.stats.edits + mw.site.stats.pages + os.time() + math.floor(os.clock() * 1000000000))
	-- math.random will throw an error if given an explicit nil parameter, so we need to use if statements to check the params.
	if first and second then
		if first <= second then -- math.random doesn't allow the first number to be greater than the second.
			return math.random(first, second)
		end
	elseif first then
		return math.random(first)
	else
		return math.random()
	end
end

--[[
order

Determine order of magnitude of a number

Usage:
{{#invoke: Math | order | value }}
]]

function wrap.order(args)
	local input_string = (args[1] or args.x or '0');
	local input_number = p._cleanNumber(input_string);
	if input_number == nil then
		return err('order of magnitude input appears non-numeric')
	else
		return p._order(input_number)
	end    
end

function p._order(x)
	if x == 0 then return 0 end
	return math.floor(math.log10(math.abs(x)))
end

--[[
precision

Detemines the precision of a number using the string representation

Usage:
{{ #invoke: Math | precision | value }}
]]

function wrap.precision(args)
	local input_string = (args[1] or args.x or '0');
	local trap_fraction = args.check_fraction;
	local input_number;

	if yesno(trap_fraction, true) then -- Returns true for all input except nil, false, "no", "n", "0" and a few others. See [[Module:Yesno]].
		local pos = string.find(input_string, '/', 1, true);
		if pos ~= nil then
			if string.find(input_string, '/', pos + 1, true) == nil then
				local denominator = string.sub(input_string, pos+1, -1);
				local denom_value = tonumber(denominator);
				if denom_value ~= nil then
					return math.log10(denom_value);
				end
			end                        
		end
	end    

	input_number, input_string = p._cleanNumber(input_string);
	if input_string == nil then
		return err('precision input appears non-numeric')
	else
		return p._precision(input_string)
	end    
end

function p._precision(x)
	if type(x) == 'number' then
		x = tostring(x)
	end
	x = string.upper(x)

	local decimal = x:find('%.')
	local exponent_pos = x:find('E')
	local result = 0;

	if exponent_pos ~= nil then
		local exponent = string.sub(x, exponent_pos + 1)
		x = string.sub(x, 1, exponent_pos - 1)
		result = result - tonumber(exponent)
	end    

	if decimal ~= nil then
		result = result + string.len(x) - decimal
		return result
	end

	local pos = string.len(x);
	while x:byte(pos) == string.byte('0') do
		pos = pos - 1
		result = result - 1
		if pos <= 0 then
			return 0
		end
	end

	return result
end

--[[
max

Finds the maximum argument

Usage:
{{#invoke:Math| max | value1 | value2 | ... }}

Note, any values that do not evaluate to numbers are ignored.
]]

function wrap.max(args)
	return p._max(unpackNumberArgs(args))
end

function p._max(...)
	local function maxOfTwo(a, b)
		if a > b then
			return a
		else
			return b
		end
	end
	local max_value = applyFuncToArgs(maxOfTwo, ...)
	if max_value then
		return max_value
	end
end

--[[
min 

Finds the minimum argument

Usage:
{{#invoke:Math| min | value1 | value2 | ... }}
OR
{{#invoke:Math| min }}

When used with no arguments, it takes its input from the parent
frame.  Note, any values that do not evaluate to numbers are ignored.
]]

function wrap.min(args)
	return p._min(unpackNumberArgs(args))
end

function p._min(...)
	local function minOfTwo(a, b)
		if a < b then
			return a
		else
			return b
		end
	end
	local min_value = applyFuncToArgs(minOfTwo, ...)
	if min_value then
		return min_value
	end
end

--[[
average 

Finds the average

Usage:
{{#invoke:Math| average | value1 | value2 | ... }}
OR
{{#invoke:Math| average }}

Note, any values that do not evaluate to numbers are ignored.
]]

function wrap.average(args)
	return p._average(unpackNumberArgs(args))
end

function p._average(...)
	local function getSum(a, b)
		return a + b
	end
	local sum, count = applyFuncToArgs(getSum, ...)
	if not sum then
		return 0
	else
		return sum / count
	end
end

--[[
round

Rounds a number to specified precision

Usage:
{{#invoke:Math | round | value | precision }}

--]]

function wrap.round(args)
	local value = p._cleanNumber(args[1] or args.value or 0)
	local precision = p._cleanNumber(args[2] or args.precision or 0)
	if value == nil or precision == nil then
		return err('round input appears non-numeric')
	else
		return p._round(value, precision)
	end    
end

function p._round(value, precision)
	local rescale = math.pow(10, precision or 0);
	return math.floor(value * rescale + 0.5) / rescale;
end

--[[
mod

Implements the modulo operator

Usage:
{{#invoke:Math | mod | x | y }}

--]]

function wrap.mod(args)
	local x = p._cleanNumber(args[1])
	local y = p._cleanNumber(args[2])
	if not x then
		return err('first argument to mod appears non-numeric')
	elseif not y then
		return err('second argument to mod appears non-numeric')
	else
		return p._mod(x, y)
	end    
end

function p._mod(x, y)
	local ret = x % y
	if not (0 <= ret and ret < y) then
		ret = 0
	end
	return ret
end

--[[
gcd

Calculates the greatest common divisor of multiple numbers

Usage:
{{#invoke:Math | gcd | value 1 | value 2 | value 3 | ... }}
--]]

function wrap.gcd(args)
	return p._gcd(unpackNumberArgs(args))
end

function p._gcd(...)
	local function findGcd(a, b)
		local r = b
		local oldr = a
		while r ~= 0 do
			local quotient = math.floor(oldr / r)
			oldr, r = r, oldr - quotient * r
		end
		if oldr < 0 then
			oldr = oldr * -1
		end
		return oldr
	end
	local result, count = applyFuncToArgs(findGcd, ...)
	return result
end

--[[
precision_format

Rounds a number to the specified precision and formats according to rules 
originally used for {{template:Rnd}}.  Output is a string.

Usage:
{{#invoke: Math | precision_format | number | precision }}
]]

function wrap.precision_format(args)
	local value_string = args[1] or 0
	local precision = args[2] or 0
	return p._precision_format(value_string, precision)
end

function p._precision_format(value_string, precision)
	-- For access to Mediawiki built-in formatter.
	local lang = mw.getContentLanguage();

	local value
	value, value_string = p._cleanNumber(value_string)
	precision = p._cleanNumber(precision)

	-- Check for non-numeric input
	if value == nil or precision == nil then
		return err('invalid input when rounding')
	end

	local current_precision = p._precision(value)
	local order = p._order(value)

	-- Due to round-off effects it is neccesary to limit the returned precision under
	-- some circumstances because the terminal digits will be inaccurately reported.
	if order + precision >= 14 then
		orig_precision = p._precision(value_string)
		if order + orig_precision >= 14 then
			precision = 13 - order;        
		end        
	end

	-- If rounding off, truncate extra digits
	if precision < current_precision then
		value = p._round(value, precision)
		current_precision = p._precision(value)
	end    

	local formatted_num = lang:formatNum(math.abs(value))
	local sign

	-- Use proper unary minus sign rather than ASCII default
	if value < 0 then
		sign = '−'
	else
		sign = ''
	end    

	-- Handle cases requiring scientific notation
	if string.find(formatted_num, 'E', 1, true) ~= nil or math.abs(order) >= 9 then
		value = value * math.pow(10, -order)
		current_precision = current_precision + order
		precision = precision + order
		formatted_num = lang:formatNum(math.abs(value))
	else
		order = 0;        
	end
	formatted_num = sign .. formatted_num

	-- Pad with zeros, if needed    
	if current_precision < precision then
		local padding
		if current_precision <= 0 then
			if precision > 0 then
				local zero_sep = lang:formatNum(1.1)
				formatted_num = formatted_num .. zero_sep:sub(2,2)

				padding = precision
				if padding > 20 then
					padding = 20
				end

				formatted_num = formatted_num .. string.rep('0', padding)
			end            
		else                   
			padding = precision - current_precision
			if padding > 20 then
				padding = 20
			end
			formatted_num = formatted_num .. string.rep('0', padding)
		end
	end

	-- Add exponential notation, if necessary.
	if order ~= 0 then
		-- Use proper unary minus sign rather than ASCII default
		if order < 0 then
			order = '−' .. lang:formatNum(math.abs(order))
		else
			order = lang:formatNum(order)
		end    

		formatted_num = formatted_num .. '<span style="margin:0 .15em 0 .25em">×</span>10<sup>' .. order .. '</sup>'
	end

	return formatted_num
end

--[[
Helper function that interprets the input numerically.  If the 
input does not appear to be a number, attempts evaluating it as
a parser functions expression.
]]

function p._cleanNumber(number_string)
	if type(number_string) == 'number' then
		-- We were passed a number, so we don't need to do any processing.
		return number_string, tostring(number_string)
	elseif type(number_string) ~= 'string' or not number_string:find('%S') then
		-- We were passed a non-string or a blank string, so exit.
		return nil, nil;
	end

	-- Attempt basic conversion
	local number = tonumber(number_string)

	-- If failed, attempt to evaluate input as an expression
	if number == nil then
		local frame = mw.getCurrentFrame()
		local attempt = frame:preprocess('{{#expr: ' .. number_string .. '}}')
		attempt = tonumber(attempt)
		if attempt ~= nil then
			number = attempt
			number_string = tostring(number)
		else
			number = nil
			number_string = nil
		end
	else
		number_string = number_string:match("^%s*(.-)%s*$") -- String is valid but may contain padding, clean it.
		number_string = number_string:match("^%+(.*)$") or number_string -- Trim any leading + signs.
		if number_string:find('^%-?0[xX]') then
			-- Number is using 0xnnn notation to indicate base 16; use the number that Lua detected instead.
			number_string = tostring(number)
		end
	end

	return number, number_string
end

--[[
Wrapper function that does basic argument processing. This ensures that all functions from #invoke can use either the current
frame or the parent frame, and it also trims whitespace for all arguments and removes blank arguments.
]]

local function makeWrapper(funcName)
	return function (frame)
		local args = getArgs(frame) -- Argument processing is left to Module:Arguments. Whitespace is trimmed and blank arguments are removed.
		return wrap[funcName](args)
	end
end

for funcName in pairs(wrap) do
	p[funcName] = makeWrapper(funcName)
end

return p