Does anyone have any good resources for math formulas/algorithms to assist with coding based on music theory principles? I thought about starting a separate topic for this, but perhaps it could just live here.
I ask because last night I was struggling with solving a problem in Lua, which can be described as:
“for a major scale defined in integers ‘0, 2, 4, 5, 7, 9, 11…’, write a function which takes a note n and an interval i, and returns a new note at that interval relative to n.” I couldn’t just rely on a hardcoded scale table because I wanted it to be dynamic and work for any note/octave/degree in the scale.
Eventually I came up with this, which seems to work
-- assumes major scale that starts at 0
local semitones = {2, 2, 1, 2, 2, 2, 1}
function findScaleDegree(note)
if note == 0 then return 1 end
local sum = 0
while true do
for i=1,#semitones do
sum = sum + semitones[i]
if sum == note then return i + 1 end
if sum > note then return 'note not in scale' end
end
end
end
function findIntervalNote(startNote, interval)
local degree = findScaleDegree(startNote)
local intervalNote = startNote
for i=0,interval-2 do
local position = (i + degree - 1) % #semitones + 1
intervalNote = intervalNote + semitones[position]
end
return intervalNote
end
-- examples
print(findIntervalNote(0, 7)) -- 11
print(findIntervalNote(2, 3)) -- 5
print(findIntervalNote(4, 9)) -- 17
I’m obviously not the first person to do this, but it also made me realize that I don’t really have any good resources for simple music theory formulas/algorithms, other than wikipedia or digging through other people’s code (which is of course a great resource as well).
The musicutil.lua library in norns is one good reference that I know of.