Module:Primes in edo

From Xenharmonic Wiki
Jump to navigation Jump to search

Documentation transcluded from /doc

Calculates approximations for prime intervals for EDOs and present them in form of a table.

See also


local p = {}

local function edoprox(edo, primes, title, prec)
  local f = 1 / edo
  local tpri = {'! colspan="2" | Prime number '}
  local tabs = {'! rowspan="2" | Error \n! absolute ([[cent|¢]]) '}
  local trel = {'! [[Relative interval error|relative]] (%) '}
  local tdeg = {'! colspan="2" | Steps ([[octave reduction|reduced]])'}
  local fmt_abs = string.format(' %%+.%df', prec)
  local fmt_rel = ' %+.0f'
  for _, p in pairs(primes) do
    s = math.log(p) / math.log(2)
    v = s*edo
    ev = math.floor(v + .5)
    table.insert(tpri, ' ' .. p)
    table.insert(tabs, string.format(fmt_abs, 1200 * (ev - v ) / edo))
    table.insert(trel, string.format(fmt_rel, 100 * (ev - v)))
    table.insert(tdeg, ' ' .. ev .. ' ('.. ev % edo .. ')')
  end
  local titleMarkup = ''
  if title then
	titleMarkup = '|-\n|+ ' .. title .. '\n'

  end
  return '{| class="wikitable center-all"\n' ..
	titleMarkup ..
	'|-\n' ..
	table.concat(tpri, '\n!') .. '\n' ..
    '|-\n' ..
    table.concat(tabs, '\n|') .. '\n' ..
    '|-\n' ..
	table.concat(trel, '\n|') .. '\n' ..
    '|-\n' ..
    table.concat(tdeg, '\n|') .. '\n' ..
    '|}'
end

local primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 }

-- evaluate input on error use default
local function eval_num_arg(input, def_value)
  local result = input
  if type(input) ~= 'number' then
    result = def_value
    if type(input) == 'string' then
      input = input:match("^%s*(.-)%s*$")
      if string.len(input) > 0 then
        result = tonumber(input)
      end
    end
  end
  return result
end

-- calculate default precicion by EDO magnitude
local function prec_by_edo(edo)
  return math.floor(math.log(edo*1.9)/math.log(10))
end

function p.primes_in_edo (frame)
  -- optional EDO number, default: 12
  local edo = eval_num_arg(frame.args['edo'], 12)
  -- optional number of columns, default: 8
  local columns = eval_num_arg(frame.args['columns'], 8)
  -- optional start column, default: start with prime 2
  local start = eval_num_arg(frame.args['start'], 1)
  local title = frame.args['title'] or 'Approximation of prime intervals in ' .. edo .. ' EDO'
  -- optional precision for abs error, default about 3 digits
  local prec = eval_num_arg(frame.args['prec'], prec_by_edo(edo))
  return edoprox( edo, {unpack(primes, start, start+columns-1)}, title, prec)
end

return p;