Modul:Math: Forskjell mellom sideversjoner
Hopp til navigering
Hopp til søk
(created random module) |
(Add precision calculation) |
||
Linje 1: | Linje 1: | ||
local |
local z = {} |
||
function |
function z.random( frame ) |
||
first = tonumber(frame.args[1]) -- if it doesn't exist it's NaN, if not a number it's nil |
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]) |
second = tonumber(frame.args[2]) |
||
Linje 13: | Linje 13: | ||
return math.random() |
return math.random() |
||
end |
end |
||
function z.precision( frame ) |
|||
return z._precision( frame.args[1] or frame.args.x or '0' ) |
|||
end |
|||
-- Determines precision of a number using the string representation |
|||
function z._precision( x ) |
|||
x = string.upper( x ) |
|||
local decimal = string.find( x, '.', 1, true ) |
|||
local exponent = string.find( x, 'E', 1, true ) |
|||
local result = 0; |
|||
if exponent ~= nil then |
|||
exponent = string.sub( x, exponent + 1 ) |
|||
x = string.sub( x, 0, exponent ) |
|||
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 |
|||
if x:byte(pos) == string.byte('.') then |
|||
pos = pos - 1 |
|||
end |
|||
end |
|||
return result |
|||
end |
|||
return z |
Sideversjonen fra 21. feb. 2013 kl. 07:40
Dokumentasjon for denne modulen kan opprettes på Modul:Math/dok
local z = {} 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 function z.precision( frame ) return z._precision( frame.args[1] or frame.args.x or '0' ) end -- Determines precision of a number using the string representation function z._precision( x ) x = string.upper( x ) local decimal = string.find( x, '.', 1, true ) local exponent = string.find( x, 'E', 1, true ) local result = 0; if exponent ~= nil then exponent = string.sub( x, exponent + 1 ) x = string.sub( x, 0, exponent ) 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 if x:byte(pos) == string.byte('.') then pos = pos - 1 end end return result end return z