Difference between revisions of "Module:Math/sandbox"

From blackwiki
Jump to navigation Jump to search
blackwiki>Mr. Stradivarius
(add structure for argument-processing code, convert the random function)
blackwiki>Mr. Stradivarius
(remove spaces inside parentheses so that the module conforms to the style guidelines)
Line 51: Line 51:
 
local input_number;
 
local input_number;
  
input_number = p._cleanNumber( frame, input_string );
+
input_number = p._cleanNumber(frame, input_string);
 
if input_number == nil then
 
if input_number == nil then
 
return '<strong class="error">Formatting error: Order of magnitude input appears non-numeric</strong>'
 
return '<strong class="error">Formatting error: Order of magnitude input appears non-numeric</strong>'
 
else
 
else
return p._order( input_number )
+
return p._order(input_number)
 
end     
 
end     
 
end
 
end
Line 76: Line 76:
 
local input_number;
 
local input_number;
  
if type( trap_fraction ) == 'string' then
+
if type(trap_fraction) == 'string' then
 
trap_fraction = trap_fraction:lower();
 
trap_fraction = trap_fraction:lower();
 
if trap_fraction == 'false' or trap_fraction == '0' or
 
if trap_fraction == 'false' or trap_fraction == '0' or
Line 87: Line 87:
  
 
if trap_fraction then
 
if trap_fraction then
local pos = string.find( input_string, '/', 1, true );
+
local pos = string.find(input_string, '/', 1, true);
 
if pos ~= nil then
 
if pos ~= nil then
if string.find( input_string, '/', pos + 1, true ) == nil then
+
if string.find(input_string, '/', pos + 1, true) == nil then
local denominator = string.sub( input_string, pos+1, -1 );
+
local denominator = string.sub(input_string, pos+1, -1);
local denom_value = tonumber( denominator );
+
local denom_value = tonumber(denominator);
 
if denom_value ~= nil then
 
if denom_value ~= nil then
 
return math.log10(denom_value);
 
return math.log10(denom_value);
Line 99: Line 99:
 
end     
 
end     
  
input_number, input_string = p._cleanNumber( frame, input_string );
+
input_number, input_string = p._cleanNumber(frame, input_string);
 
if input_string == nil then
 
if input_string == nil then
 
return '<strong class="error">Formatting error: Precision input appears non-numeric</strong>'
 
return '<strong class="error">Formatting error: Precision input appears non-numeric</strong>'
 
else
 
else
return p._precision( input_string )
+
return p._precision(input_string)
 
end     
 
end     
 
end
 
end
function p._precision( x )     
+
function p._precision(x)     
x = string.upper( x )
+
x = string.upper(x)
  
local decimal = string.find( x, '.', 1, true )
+
local decimal = string.find(x, '.', 1, true)
local exponent_pos = string.find( x, 'E', 1, true )
+
local exponent_pos = string.find(x, 'E', 1, true)
 
local result = 0;
 
local result = 0;
  
 
if exponent_pos ~= nil then
 
if exponent_pos ~= nil then
local exponent = string.sub( x, exponent_pos + 1 )
+
local exponent = string.sub(x, exponent_pos + 1)
x = string.sub( x, 1, exponent_pos - 1 )
+
x = string.sub(x, 1, exponent_pos - 1)
result = result - tonumber( exponent )
+
result = result - tonumber(exponent)
 
end     
 
end     
  
 
if decimal ~= nil then
 
if decimal ~= nil then
result = result + string.len( x ) - decimal
+
result = result + string.len(x) - decimal
 
return result
 
return result
 
end
 
end
  
local pos = string.len( x );
+
local pos = string.len(x);
 
while x:byte(pos) == string.byte('0') do
 
while x:byte(pos) == string.byte('0') do
 
pos = pos - 1
 
pos = pos - 1
Line 149: Line 149:
 
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 p.max( frame )
+
function p.max(frame)
 
local args = frame.args;
 
local args = frame.args;
  
Line 160: Line 160:
 
local i = 1;
 
local i = 1;
 
while args[i] ~= nil do
 
while args[i] ~= nil do
local val = p._cleanNumber( frame, args[i] );
+
local val = p._cleanNumber(frame, args[i]);
 
if val ~= nil then
 
if val ~= nil then
 
if max_value == nil or val > max_value then
 
if max_value == nil or val > max_value then
Line 185: Line 185:
 
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 p.min( frame )
+
function p.min(frame)
 
local args = frame.args;
 
local args = frame.args;
  
Line 196: Line 196:
 
local i = 1;
 
local i = 1;
 
while args[i] ~= nil do
 
while args[i] ~= nil do
local val = p._cleanNumber( frame, args[i] );
+
local val = p._cleanNumber(frame, args[i]);
 
if val ~= nil then
 
if val ~= nil then
 
if min_value == nil or val < min_value then
 
if min_value == nil or val < min_value then
Line 221: Line 221:
 
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 p.average( frame )
+
function p.average(frame)
 
local args = frame.args;
 
local args = frame.args;
 
if args[1] == nil then
 
if args[1] == nil then
Line 232: Line 232:
 
local i = 1;
 
local i = 1;
 
while args[i] ~= nil do
 
while args[i] ~= nil do
local val = p._cleanNumber( frame, args[i] );
+
local val = p._cleanNumber(frame, args[i]);
 
if val ~= nil then
 
if val ~= nil then
 
sum = sum + val
 
sum = sum + val
Line 255: Line 255:
 
local value, precision;
 
local value, precision;
  
value = p._cleanNumber( frame, frame.args[1] or frame.args.value or 0 );
+
value = p._cleanNumber(frame, frame.args[1] or frame.args.value or 0);
precision = p._cleanNumber( frame, frame.args[2] or frame.args.precision or 0 );
+
precision = p._cleanNumber(frame, frame.args[2] or frame.args.precision or 0);
  
 
if value == nil or precision == nil then
 
if value == nil or precision == nil then
 
return '<strong class="error">Formatting error: Round input appears non-numeric</strong>'
 
return '<strong class="error">Formatting error: Round input appears non-numeric</strong>'
 
else
 
else
return p._round( value, precision );
+
return p._round(value, precision);
 
end     
 
end     
 
end
 
end
function p._round( value, precision )
+
function p._round(value, precision)
local rescale = math.pow( 10, precision );
+
local rescale = math.pow(10, precision);
return math.floor( value * rescale + 0.5 ) / rescale;
+
return math.floor(value * rescale + 0.5) / rescale;
 
end
 
end
  
Line 310: Line 310:
 
{{#invoke: Math | precision_format | number | precision }}
 
{{#invoke: Math | precision_format | number | precision }}
 
]]
 
]]
function p.precision_format( frame )
+
function p.precision_format(frame)
 
-- For access to Mediawiki built-in formatter.
 
-- For access to Mediawiki built-in formatter.
 
local lang = mw.getContentLanguage();
 
local lang = mw.getContentLanguage();
  
 
local value_string, value, precision;
 
local value_string, value, precision;
value, value_string = p._cleanNumber( frame, frame.args[1] or 0 );
+
value, value_string = p._cleanNumber(frame, frame.args[1] or 0);
precision = p._cleanNumber( frame, frame.args[2] or 0 );
+
precision = p._cleanNumber(frame, frame.args[2] or 0);
  
 
-- Check for non-numeric input
 
-- Check for non-numeric input
Line 323: Line 323:
 
end
 
end
  
local current_precision = p._precision( value );
+
local current_precision = p._precision(value);
  
local order = p._order( value );
+
local order = p._order(value);
  
 
-- Due to round-off effects it is neccesary to limit the returned precision under
 
-- Due to round-off effects it is neccesary to limit the returned precision under
 
-- some circumstances because the terminal digits will be inaccurately reported.
 
-- some circumstances because the terminal digits will be inaccurately reported.
 
if order + precision >= 14 then
 
if order + precision >= 14 then
orig_precision = p._precision( value_string );
+
orig_precision = p._precision(value_string);
 
if order + orig_precision >= 14 then
 
if order + orig_precision >= 14 then
 
precision = 13 - order;         
 
precision = 13 - order;         
Line 338: Line 338:
 
-- If rounding off, truncate extra digits
 
-- If rounding off, truncate extra digits
 
if precision < current_precision then
 
if precision < current_precision then
value = p._round( value, precision );
+
value = p._round(value, precision);
current_precision = p._precision( value );
+
current_precision = p._precision(value);
 
end     
 
end     
  
local formatted_num = lang:formatNum( math.abs(value) );
+
local formatted_num = lang:formatNum(math.abs(value));
 
local sign;
 
local sign;
  
Line 353: Line 353:
  
 
-- Handle cases requiring scientific notation
 
-- Handle cases requiring scientific notation
if string.find( formatted_num, 'E', 1, true ) ~= nil or math.abs(order) >= 9 then
+
if string.find(formatted_num, 'E', 1, true) ~= nil or math.abs(order) >= 9 then
value = value * math.pow( 10, -order );
+
value = value * math.pow(10, -order);
 
current_precision = current_precision + order;
 
current_precision = current_precision + order;
 
precision = precision + order;
 
precision = precision + order;
formatted_num = lang:formatNum( math.abs(value) );
+
formatted_num = lang:formatNum(math.abs(value));
 
else
 
else
 
order = 0;         
 
order = 0;         
Line 368: Line 368:
 
if current_precision <= 0 then
 
if current_precision <= 0 then
 
if precision > 0 then
 
if precision > 0 then
local zero_sep = lang:formatNum( 1.1 );
+
local zero_sep = lang:formatNum(1.1);
 
formatted_num = formatted_num .. zero_sep:sub(2,2);
 
formatted_num = formatted_num .. zero_sep:sub(2,2);
  
Line 376: Line 376:
 
end
 
end
  
formatted_num = formatted_num .. string.rep( '0', padding );
+
formatted_num = formatted_num .. string.rep('0', padding);
 
end             
 
end             
 
else                   
 
else                   
Line 383: Line 383:
 
padding = 20;
 
padding = 20;
 
end
 
end
formatted_num = formatted_num .. string.rep( '0', padding );
+
formatted_num = formatted_num .. string.rep('0', padding);
 
end
 
end
 
end
 
end
Line 391: Line 391:
 
-- Use proper unary minus sign rather than ASCII default
 
-- Use proper unary minus sign rather than ASCII default
 
if order < 0 then
 
if order < 0 then
order = '−' .. lang:formatNum( math.abs(order) );
+
order = '−' .. lang:formatNum(math.abs(order));
 
else
 
else
order = lang:formatNum( order );
+
order = lang:formatNum(order);
 
end     
 
end     
  
Line 408: Line 408:
 
]]
 
]]
  
function p._cleanNumber( frame, number_string )
+
function p._cleanNumber(frame, number_string)
 
if number_string == nil or number_string:len() == 0 then
 
if number_string == nil or number_string:len() == 0 then
 
return nil, nil;
 
return nil, nil;
Line 414: Line 414:
  
 
-- Attempt basic conversion
 
-- Attempt basic conversion
local number = tonumber( number_string )
+
local number = tonumber(number_string)
  
 
-- If failed, attempt to evaluate input as an expression
 
-- If failed, attempt to evaluate input as an expression
 
if number == nil then         
 
if number == nil then         
local attempt = frame:preprocess( '{{#expr: ' .. number_string .. '}}' );
+
local attempt = frame:preprocess('{{#expr: ' .. number_string .. '}}');
attempt = tonumber( attempt );
+
attempt = tonumber(attempt);
 
if attempt ~= nil then
 
if attempt ~= nil then
 
number = attempt;
 
number = attempt;
number_string = tostring( number );
+
number_string = tostring(number);
 
else
 
else
 
number = nil;
 
number = nil;
Line 432: Line 432:
 
else
 
else
 
-- String is valid but may contain padding, clean it.
 
-- String is valid but may contain padding, clean it.
number_string = number_string:match( "^%s*(.-)%s*$" );
+
number_string = number_string:match("^%s*(.-)%s*$");
 
end
 
end
  

Revision as of 12:41, 5 December 2013

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

--[[

This module provides a number of basic mathematical operations.

]]

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.

--[[
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 = tonumber(args[1])
	local second = tonumber(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 = (frame.args[1] or frame.args.x or '0');
	local input_number;

	input_number = p._cleanNumber(frame, input_string);
	if input_number == nil then
		return '<strong class="error">Formatting error: Order of magnitude input appears non-numeric</strong>'
	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 = (frame.args[1] or frame.args.x or '0');
	local trap_fraction = frame.args.check_fraction or false;
	local input_number;

	if type(trap_fraction) == 'string' then
		trap_fraction = trap_fraction:lower();
		if trap_fraction == 'false' or trap_fraction == '0' or
			trap_fraction == 'no' or trap_fraction == '' then
			trap_fraction = false;
		else
			trap_fraction = true;
		end
	end

	if trap_fraction then
		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(frame, input_string);
	if input_string == nil then
		return '<strong class="error">Formatting error: Precision input appears non-numeric</strong>'
	else
		return p._precision(input_string)
	end    
end
function p._precision(x)    
	x = string.upper(x)

	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

--[[
max

Finds the maximum argument

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

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 p.max(frame)
	local args = frame.args;

	if args[1] == nil then
		local parent = frame:getParent();
		args = parent.args;
	end
	local max_value = nil;

	local i = 1;
	while args[i] ~= nil do
		local val = p._cleanNumber(frame, args[i]);
		if val ~= nil then
			if max_value == nil or val > max_value then
				max_value = val;
			end
		end        
		i = i + 1;
	end

	return max_value
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 p.min(frame)
	local args = frame.args;

	if args[1] == nil then
		local parent = frame:getParent();
		args = parent.args;
	end
	local min_value = nil;

	local i = 1;
	while args[i] ~= nil do
		local val = p._cleanNumber(frame, args[i]);
		if val ~= nil then
			if min_value == nil or val < min_value then
				min_value = val;
			end
		end        
		i = i + 1;
	end

	return min_value
end

--[[
average 

Finds the average

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

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 p.average(frame)
	local args = frame.args;
	if args[1] == nil then
		local parent = frame:getParent();
		args = parent.args;
	end
	local sum = 0;
	local count = 0;

	local i = 1;
	while args[i] ~= nil do
		local val = p._cleanNumber(frame, args[i]);
		if val ~= nil then
			sum = sum + val
			count = count + 1
		end        
		i = i + 1;
	end

	return (count == 0 and 0 or sum/count)
end

--[[
round

Rounds a number to specified precision

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

--]]
function p.round(frame)
	local value, precision;

	value = p._cleanNumber(frame, frame.args[1] or frame.args.value or 0);
	precision = p._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 p._round(value, precision);
	end    
end
function p._round(value, precision)
	local rescale = math.pow(10, precision);
	return math.floor(value * rescale + 0.5) / rescale;
end

--[=[
gcd

Calculates the [[greatest common divisor]] of two numbers according to the [[extended Euclidean algorithm]].

Usage:
{{#invoke:Math | gcd | value 1 | value 2 }}
]=]
function p.gcd(frame)
	local args = frame.args

	if args[1] == nil then
		local parent = frame:getParent()
		args = parent.args
	end

	local a = p._cleanNumber(frame, args[1])
	local b = p._cleanNumber(frame, args[2])
	if not a or not b then return end

	local r = b
	local oldr = a
	while r ~= 0 do
		local quotient = math.floor(oldr / r)
		oldr, r = r, oldr - quotient * r
	end

	if a == 0 and b < 0 or b == 0 and a < 0 then oldr = oldr * -1 end

	return oldr
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 p.precision_format(frame)
	-- For access to Mediawiki built-in formatter.
	local lang = mw.getContentLanguage();

	local value_string, value, precision;
	value, value_string = p._cleanNumber(frame, frame.args[1] or 0);
	precision = p._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 = 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(frame, number_string)
	if number_string == nil or number_string:len() == 0 then
		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 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
	elseif type(number_string) == 'number' then
		-- We were passed a number, so we need to convert number_string to a string.
		number_string = tostring(number)
	else
		-- String is valid but may contain padding, clean it.
		number_string = number_string:match("^%s*(.-)%s*$");
	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)
		-- If called via #invoke, use the args passed into the invoking template, or the args passed to #invoke if any exist.
		-- Otherwise assume args are being passed directly in from the debug console or from another Lua module.
		local origArgs
		if frame == mw.getCurrentFrame() then
			origArgs = frame:getParent().args
			for k, v in pairs(frame.args) do
				origArgs = frame.args
				break
			end
		else
			origArgs = frame
		end
		-- Trim whitespace and remove blank arguments.
		local args = {}
		for k, v in pairs(origArgs) do
			if type(v) == 'string' then
				v = mw.text.trim(v)
			end
			if v ~= '' then
				args[k] = v
			end
		end
		return wrap[funcName](args)
	end
end

local funcNames = {'random', 'order', 'precision', 'max', 'min', 'average', 'round', 'gcd'}
for _, funcName in ipairs(funcNames) do
	p[funcName] = makeWrapper(funcName)
end

return p