https://wiki.seshstation.com/index.php?title=Module:Math&feed=atom&action=historyModule:Math - Revision history2024-03-28T20:03:27ZRevision history for this page on the wikiMediaWiki 1.36.1https://wiki.seshstation.com/index.php?title=Module:Math&diff=361&oldid=prevSESHstation: 1 revision imported2021-11-21T11:00:40Z<p>1 revision imported</p>
<table style="background-color: #fff; color: #202122;" data-mw="interface">
<col class="diff-marker" />
<col class="diff-content" />
<col class="diff-marker" />
<col class="diff-content" />
<tr class="diff-title" lang="en">
<td colspan="2" style="background-color: #fff; color: #202122; text-align: center;">← Older revision</td>
<td colspan="2" style="background-color: #fff; color: #202122; text-align: center;">Revision as of 11:00, 21 November 2021</td>
</tr>
<!-- diff cache key wikiseshstation572:diff::1.12:old-360:rev-361 -->
</table>SESHstationhttps://wiki.seshstation.com/index.php?title=Module:Math&diff=360&oldid=prevtmpl>Primefac: typo fix2021-03-11T22:23:48Z<p>typo fix</p>
<p><b>New page</b></p><div>--[[<br />
<br />
This module provides a number of basic mathematical operations.<br />
<br />
]]<br />
<br />
local yesno, getArgs -- lazily initialized<br />
<br />
local p = {} -- Holds functions to be returned from #invoke, and functions to make available to other Lua modules.<br />
local wrap = {} -- Holds wrapper functions that process arguments from #invoke. These act as intemediary between functions meant for #invoke and functions meant for Lua.<br />
<br />
--[[<br />
Helper functions used to avoid redundant code.<br />
]]<br />
<br />
local function err(msg)<br />
-- Generates wikitext error messages.<br />
return mw.ustring.format('<strong class="error">Formatting error: %s</strong>', msg)<br />
end<br />
<br />
local function unpackNumberArgs(args)<br />
-- Returns an unpacked list of arguments specified with numerical keys.<br />
local ret = {}<br />
for k, v in pairs(args) do<br />
if type(k) == 'number' then<br />
table.insert(ret, v)<br />
end<br />
end<br />
return unpack(ret)<br />
end<br />
<br />
local function makeArgArray(...)<br />
-- Makes an array of arguments from a list of arguments that might include nils.<br />
local args = {...} -- Table of arguments. It might contain nils or non-number values, so we can't use ipairs.<br />
local nums = {} -- Stores the numbers of valid numerical arguments.<br />
local ret = {}<br />
for k, v in pairs(args) do<br />
v = p._cleanNumber(v)<br />
if v then<br />
nums[#nums + 1] = k<br />
args[k] = v<br />
end<br />
end<br />
table.sort(nums)<br />
for i, num in ipairs(nums) do<br />
ret[#ret + 1] = args[num]<br />
end<br />
return ret<br />
end<br />
<br />
local function fold(func, ...)<br />
-- Use a function on all supplied arguments, and return the result. The function must accept two numbers as parameters,<br />
-- and must return a number as an output. This number is then supplied as input to the next function call.<br />
local vals = makeArgArray(...)<br />
local count = #vals -- The number of valid arguments<br />
if count == 0 then return<br />
-- Exit if we have no valid args, otherwise removing the first arg would cause an error.<br />
nil, 0<br />
end<br />
local ret = table.remove(vals, 1)<br />
for _, val in ipairs(vals) do<br />
ret = func(ret, val)<br />
end<br />
return ret, count<br />
end<br />
<br />
--[[<br />
Fold arguments by selectively choosing values (func should return when to choose the current "dominant" value).<br />
]]<br />
local function binary_fold(func, ...)<br />
local value = fold((function(a, b) if func(a, b) then return a else return b end end), ...)<br />
return value<br />
end<br />
<br />
--[[<br />
random<br />
<br />
Generate a random number<br />
<br />
Usage:<br />
{{#invoke: Math | random }}<br />
{{#invoke: Math | random | maximum value }}<br />
{{#invoke: Math | random | minimum value | maximum value }}<br />
]]<br />
<br />
function wrap.random(args)<br />
local first = p._cleanNumber(args[1])<br />
local second = p._cleanNumber(args[2])<br />
return p._random(first, second)<br />
end<br />
<br />
function p._random(first, second)<br />
math.randomseed(mw.site.stats.edits + mw.site.stats.pages + os.time() + math.floor(os.clock() * 1000000000))<br />
-- math.random will throw an error if given an explicit nil parameter, so we need to use if statements to check the params.<br />
if first and second then<br />
if first <= second then -- math.random doesn't allow the first number to be greater than the second.<br />
return math.random(first, second)<br />
end<br />
elseif first then<br />
return math.random(first)<br />
else<br />
return math.random()<br />
end<br />
end<br />
<br />
--[[<br />
order<br />
<br />
Determine order of magnitude of a number<br />
<br />
Usage:<br />
{{#invoke: Math | order | value }}<br />
]]<br />
<br />
function wrap.order(args)<br />
local input_string = (args[1] or args.x or '0');<br />
local input_number = p._cleanNumber(input_string);<br />
if input_number == nil then<br />
return err('order of magnitude input appears non-numeric')<br />
else<br />
return p._order(input_number)<br />
end<br />
end<br />
<br />
function p._order(x)<br />
if x == 0 then return 0 end<br />
return math.floor(math.log10(math.abs(x)))<br />
end<br />
<br />
--[[<br />
precision<br />
<br />
Detemines the precision of a number using the string representation<br />
<br />
Usage:<br />
{{ #invoke: Math | precision | value }}<br />
]]<br />
<br />
function wrap.precision(args)<br />
local input_string = (args[1] or args.x or '0');<br />
local trap_fraction = args.check_fraction;<br />
local input_number;<br />
<br />
if not yesno then<br />
yesno = require('Module:Yesno')<br />
end<br />
if yesno(trap_fraction, true) then -- Returns true for all input except nil, false, "no", "n", "0" and a few others. See [[Module:Yesno]].<br />
local pos = string.find(input_string, '/', 1, true);<br />
if pos ~= nil then<br />
if string.find(input_string, '/', pos + 1, true) == nil then<br />
local denominator = string.sub(input_string, pos+1, -1);<br />
local denom_value = tonumber(denominator);<br />
if denom_value ~= nil then<br />
return math.log10(denom_value);<br />
end<br />
end<br />
end<br />
end<br />
<br />
input_number, input_string = p._cleanNumber(input_string);<br />
if input_string == nil then<br />
return err('precision input appears non-numeric')<br />
else<br />
return p._precision(input_string)<br />
end<br />
end<br />
<br />
function p._precision(x)<br />
if type(x) == 'number' then<br />
x = tostring(x)<br />
end<br />
x = string.upper(x)<br />
<br />
local decimal = x:find('%.')<br />
local exponent_pos = x:find('E')<br />
local result = 0;<br />
<br />
if exponent_pos ~= nil then<br />
local exponent = string.sub(x, exponent_pos + 1)<br />
x = string.sub(x, 1, exponent_pos - 1)<br />
result = result - tonumber(exponent)<br />
end<br />
<br />
if decimal ~= nil then<br />
result = result + string.len(x) - decimal<br />
return result<br />
end<br />
<br />
local pos = string.len(x);<br />
while x:byte(pos) == string.byte('0') do<br />
pos = pos - 1<br />
result = result - 1<br />
if pos <= 0 then<br />
return 0<br />
end<br />
end<br />
<br />
return result<br />
end<br />
<br />
<br />
--[[<br />
max<br />
<br />
Finds the maximum argument<br />
<br />
Usage:<br />
{{#invoke:Math| max | value1 | value2 | ... }}<br />
<br />
Note, any values that do not evaluate to numbers are ignored.<br />
]]<br />
<br />
function wrap.max(args)<br />
return p._max(unpackNumberArgs(args))<br />
end<br />
<br />
function p._max(...)<br />
local max_value = binary_fold((function(a, b) return a > b end), ...)<br />
if max_value then<br />
return max_value<br />
end<br />
end<br />
<br />
--[[<br />
median<br />
<br />
Find the median of set of numbers<br />
<br />
Usage:<br />
{{#invoke:Math | median | number1 | number2 | ...}}<br />
OR<br />
{{#invoke:Math | median }}<br />
]]<br />
<br />
function wrap.median(args)<br />
return p._median(unpackNumberArgs(args))<br />
end<br />
<br />
function p._median(...)<br />
local vals = makeArgArray(...)<br />
local count = #vals<br />
table.sort(vals)<br />
<br />
if count == 0 then<br />
return 0<br />
end<br />
<br />
if p._mod(count, 2) == 0 then<br />
return (vals[count/2] + vals[count/2+1])/2<br />
else<br />
return vals[math.ceil(count/2)]<br />
end<br />
end<br />
<br />
--[[<br />
min<br />
<br />
Finds the minimum argument<br />
<br />
Usage:<br />
{{#invoke:Math| min | value1 | value2 | ... }}<br />
OR<br />
{{#invoke:Math| min }}<br />
<br />
When used with no arguments, it takes its input from the parent<br />
frame. Note, any values that do not evaluate to numbers are ignored.<br />
]]<br />
<br />
function wrap.min(args)<br />
return p._min(unpackNumberArgs(args))<br />
end<br />
<br />
function p._min(...)<br />
local min_value = binary_fold((function(a, b) return a < b end), ...)<br />
if min_value then<br />
return min_value<br />
end<br />
end<br />
<br />
--[[<br />
sum<br />
<br />
Finds the sum<br />
<br />
Usage:<br />
{{#invoke:Math| sum | value1 | value2 | ... }}<br />
OR<br />
{{#invoke:Math| sum }}<br />
<br />
Note, any values that do not evaluate to numbers are ignored.<br />
]]<br />
<br />
function wrap.sum(args)<br />
return p._sum(unpackNumberArgs(args))<br />
end<br />
<br />
function p._sum(...)<br />
local sums, count = fold((function(a, b) return a + b end), ...)<br />
if not sums then<br />
return 0<br />
else<br />
return sums<br />
end<br />
end<br />
<br />
--[[<br />
average<br />
<br />
Finds the average<br />
<br />
Usage:<br />
{{#invoke:Math| average | value1 | value2 | ... }}<br />
OR<br />
{{#invoke:Math| average }}<br />
<br />
Note, any values that do not evaluate to numbers are ignored.<br />
]]<br />
<br />
function wrap.average(args)<br />
return p._average(unpackNumberArgs(args))<br />
end<br />
<br />
function p._average(...)<br />
local sum, count = fold((function(a, b) return a + b end), ...)<br />
if not sum then<br />
return 0<br />
else<br />
return sum / count<br />
end<br />
end<br />
<br />
--[[<br />
round<br />
<br />
Rounds a number to specified precision<br />
<br />
Usage:<br />
{{#invoke:Math | round | value | precision }}<br />
<br />
--]]<br />
<br />
function wrap.round(args)<br />
local value = p._cleanNumber(args[1] or args.value or 0)<br />
local precision = p._cleanNumber(args[2] or args.precision or 0)<br />
if value == nil or precision == nil then<br />
return err('round input appears non-numeric')<br />
else<br />
return p._round(value, precision)<br />
end<br />
end<br />
<br />
function p._round(value, precision)<br />
local rescale = math.pow(10, precision or 0);<br />
return math.floor(value * rescale + 0.5) / rescale;<br />
end<br />
<br />
--[[<br />
log10<br />
<br />
returns the log (base 10) of a number<br />
<br />
Usage:<br />
{{#invoke:Math | log10 | x }}<br />
]]<br />
<br />
function wrap.log10(args)<br />
return math.log10(args[1])<br />
end<br />
<br />
--[[<br />
mod<br />
<br />
Implements the modulo operator<br />
<br />
Usage:<br />
{{#invoke:Math | mod | x | y }}<br />
<br />
--]]<br />
<br />
function wrap.mod(args)<br />
local x = p._cleanNumber(args[1])<br />
local y = p._cleanNumber(args[2])<br />
if not x then<br />
return err('first argument to mod appears non-numeric')<br />
elseif not y then<br />
return err('second argument to mod appears non-numeric')<br />
else<br />
return p._mod(x, y)<br />
end<br />
end<br />
<br />
function p._mod(x, y)<br />
local ret = x % y<br />
if not (0 <= ret and ret < y) then<br />
ret = 0<br />
end<br />
return ret<br />
end<br />
<br />
--[[<br />
gcd<br />
<br />
Calculates the greatest common divisor of multiple numbers<br />
<br />
Usage:<br />
{{#invoke:Math | gcd | value 1 | value 2 | value 3 | ... }}<br />
--]]<br />
<br />
function wrap.gcd(args)<br />
return p._gcd(unpackNumberArgs(args))<br />
end<br />
<br />
function p._gcd(...)<br />
local function findGcd(a, b)<br />
local r = b<br />
local oldr = a<br />
while r ~= 0 do<br />
local quotient = math.floor(oldr / r)<br />
oldr, r = r, oldr - quotient * r<br />
end<br />
if oldr < 0 then<br />
oldr = oldr * -1<br />
end<br />
return oldr<br />
end<br />
local result, count = fold(findGcd, ...)<br />
return result<br />
end<br />
<br />
--[[<br />
precision_format<br />
<br />
Rounds a number to the specified precision and formats according to rules<br />
originally used for {{template:Rnd}}. Output is a string.<br />
<br />
Usage:<br />
{{#invoke: Math | precision_format | number | precision }}<br />
]]<br />
<br />
function wrap.precision_format(args)<br />
local value_string = args[1] or 0<br />
local precision = args[2] or 0<br />
return p._precision_format(value_string, precision)<br />
end<br />
<br />
function p._precision_format(value_string, precision)<br />
-- For access to Mediawiki built-in formatter.<br />
local lang = mw.getContentLanguage();<br />
<br />
local value<br />
value, value_string = p._cleanNumber(value_string)<br />
precision = p._cleanNumber(precision)<br />
<br />
-- Check for non-numeric input<br />
if value == nil or precision == nil then<br />
return err('invalid input when rounding')<br />
end<br />
<br />
local current_precision = p._precision(value)<br />
local order = p._order(value)<br />
<br />
-- Due to round-off effects it is neccesary to limit the returned precision under<br />
-- some circumstances because the terminal digits will be inaccurately reported.<br />
if order + precision >= 14 then<br />
if order + p._precision(value_string) >= 14 then<br />
precision = 13 - order;<br />
end<br />
end<br />
<br />
-- If rounding off, truncate extra digits<br />
if precision < current_precision then<br />
value = p._round(value, precision)<br />
current_precision = p._precision(value)<br />
end<br />
<br />
local formatted_num = lang:formatNum(math.abs(value))<br />
local sign<br />
<br />
-- Use proper unary minus sign rather than ASCII default<br />
if value < 0 then<br />
sign = '−'<br />
else<br />
sign = ''<br />
end<br />
<br />
-- Handle cases requiring scientific notation<br />
if string.find(formatted_num, 'E', 1, true) ~= nil or math.abs(order) >= 9 then<br />
value = value * math.pow(10, -order)<br />
current_precision = current_precision + order<br />
precision = precision + order<br />
formatted_num = lang:formatNum(math.abs(value))<br />
else<br />
order = 0;<br />
end<br />
formatted_num = sign .. formatted_num<br />
<br />
-- Pad with zeros, if needed<br />
if current_precision < precision then<br />
local padding<br />
if current_precision <= 0 then<br />
if precision > 0 then<br />
local zero_sep = lang:formatNum(1.1)<br />
formatted_num = formatted_num .. zero_sep:sub(2,2)<br />
<br />
padding = precision<br />
if padding > 20 then<br />
padding = 20<br />
end<br />
<br />
formatted_num = formatted_num .. string.rep('0', padding)<br />
end<br />
else<br />
padding = precision - current_precision<br />
if padding > 20 then<br />
padding = 20<br />
end<br />
formatted_num = formatted_num .. string.rep('0', padding)<br />
end<br />
end<br />
<br />
-- Add exponential notation, if necessary.<br />
if order ~= 0 then<br />
-- Use proper unary minus sign rather than ASCII default<br />
if order < 0 then<br />
order = '−' .. lang:formatNum(math.abs(order))<br />
else<br />
order = lang:formatNum(order)<br />
end<br />
<br />
formatted_num = formatted_num .. '<span style="margin:0 .15em 0 .25em">×</span>10<sup>' .. order .. '</sup>'<br />
end<br />
<br />
return formatted_num<br />
end<br />
<br />
--[[<br />
divide<br />
<br />
Implements the division operator<br />
<br />
Usage:<br />
{{#invoke:Math | divide | x | y | round= | precision= }}<br />
<br />
--]]<br />
function wrap.divide(args)<br />
local x = args[1]<br />
local y = args[2]<br />
local round = args.round<br />
local precision = args.precision<br />
if not yesno then<br />
yesno = require('Module:Yesno')<br />
end<br />
return p._divide(x, y, yesno(round), precision)<br />
end<br />
<br />
function p._divide(x, y, round, precision)<br />
if y == nil or y == "" then<br />
return err("Empty divisor")<br />
elseif not tonumber(y) then<br />
if type(y) == 'string' and string.sub(y, 1, 1) == '<' then<br />
return y<br />
else<br />
return err("Not a number: " .. y)<br />
end<br />
elseif x == nil or x == "" then<br />
return err("Empty dividend")<br />
elseif not tonumber(x) then<br />
if type(x) == 'string' and string.sub(x, 1, 1) == '<' then<br />
return x<br />
else<br />
return err("Not a number: " .. x)<br />
end<br />
else<br />
local z = x / y<br />
if round then<br />
return p._round(z, 0)<br />
elseif precision then<br />
return p._round(z, precision)<br />
else<br />
return z <br />
end<br />
end<br />
end<br />
<br />
--[[<br />
Helper function that interprets the input numerically. If the<br />
input does not appear to be a number, attempts evaluating it as<br />
a parser functions expression.<br />
]]<br />
<br />
function p._cleanNumber(number_string)<br />
if type(number_string) == 'number' then<br />
-- We were passed a number, so we don't need to do any processing.<br />
return number_string, tostring(number_string)<br />
elseif type(number_string) ~= 'string' or not number_string:find('%S') then<br />
-- We were passed a non-string or a blank string, so exit.<br />
return nil, nil;<br />
end<br />
<br />
-- Attempt basic conversion<br />
local number = tonumber(number_string)<br />
<br />
-- If failed, attempt to evaluate input as an expression<br />
if number == nil then<br />
local success, result = pcall(mw.ext.ParserFunctions.expr, number_string)<br />
if success then<br />
number = tonumber(result)<br />
number_string = tostring(number)<br />
else<br />
number = nil<br />
number_string = nil<br />
end<br />
else<br />
number_string = number_string:match("^%s*(.-)%s*$") -- String is valid but may contain padding, clean it.<br />
number_string = number_string:match("^%+(.*)$") or number_string -- Trim any leading + signs.<br />
if number_string:find('^%-?0[xX]') then<br />
-- Number is using 0xnnn notation to indicate base 16; use the number that Lua detected instead.<br />
number_string = tostring(number)<br />
end<br />
end<br />
<br />
return number, number_string<br />
end<br />
<br />
--[[<br />
Wrapper function that does basic argument processing. This ensures that all functions from #invoke can use either the current<br />
frame or the parent frame, and it also trims whitespace for all arguments and removes blank arguments.<br />
]]<br />
<br />
local mt = { __index = function(t, k)<br />
return function(frame)<br />
if not getArgs then<br />
getArgs = require('Module:Arguments').getArgs<br />
end<br />
return wrap[k](getArgs(frame)) -- Argument processing is left to Module:Arguments. Whitespace is trimmed and blank arguments are removed.<br />
end<br />
end }<br />
<br />
return setmetatable(p, mt)</div>tmpl>Primefac