Module:Math

Revision as of 20:37, 21 February 2013 by m>Dragons flight (can't work due to prehandling by #expr, simplify)

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

local z = {}

-- Generate random number
function z.random( frame )
    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
        if first <= second then -- could match if both nil, but already checked that first is a number in last line
            return math.random(first, second)
        end
        return math.random(first)
    end   
    return math.random()
end

-- Determine order of magnitude
function z.order(frame)
    return z._order(tonumber(frame.args[1] or frame.args.x or 0))
end
function z._order(x)
    if x == 0 then return 0 end
    return math.floor(math.log10(math.abs(x)))
end

-- Determines precision of a number using the string representation
function z.precision( frame )
    return z._precision( frame.args[1] or frame.args.x or '0' )
end
function z._precision( x )
    x = string.upper( x )

    -- Remove leading / trailing whitespace
    x = x:match "^%s*(.-)%s*$";

    local decimal = string.find( x, '.', 1, true )
    local exponent_pos = string.find( x, 'E', 1, true )
    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

-- Finds maximum argument
function z.max( frame )
    if frame.args[1] == nil then
        return ''
    end
    local max_value = tonumber( frame.args[1] )
    
    local i = 2;
    while frame.args[i] ~= nil do
        local val = tonumber( frame.args[i] );
        if val ~= nil then
            if val > max_value then
                max_value = val;
            end
        end        
        i = i + 1;
    end
  
    return max_value
end

-- Finds minimum argument
function z.min( frame )
    if frame.args[1] == nil then
        return ''
    end
    local min_value = tonumber( frame.args[1] )
    
    local i = 2;
    while frame.args[i] ~= nil do
        local val = tonumber( frame.args[i] );
        if val ~= nil then
            if val < min_value then
                min_value = val;
            end
        end        
        i = i + 1;
    end
  
    return min_value
end

-- Rounds a number to the specified precision and formats according to rules 
-- originally used for {{template:Rnd}}
function z.round( frame )
    -- For access to Mediawiki built-in formatter.
    local lang = mw.getContentLanguage();
    
    local value = tonumber( frame.args[1] or 0 );
    local precision = tonumber( frame.args[2] or 0 );
    local current_precision = z._precision( value );

    local order = z._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
        precision = 13 - order;        
    end

    -- If rounding off, truncate extra digits
    if precision < current_precision then
        local rescale = math.pow( 10, precision );
        value = math.floor( value * rescale + 0.5 ) / rescale;
        current_precision = z._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
        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);
                formatted_num = formatted_num .. string.rep( '0', precision );
            end            
        else       
            formatted_num = formatted_num .. string.rep( '0', precision - current_precision );
        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

return z