In just intonation theory, a type of music theory, intervals between notes are expressed with rational numbers. Doubling a frequency with a 2:1 ratio brings it up an octave and a 1:1 ratio is no change; a unison. So if I have an interval n that is larger than an octave or smaller than a unison (it goes down), it is useful to 'justify' it. That is, to make 1 ≤ n ≤ 2. I've been doing this in Python with the following function:
def justify(n):
return n / 2 ** floor( log(n,2) )
The actual function involves the fractions library, but this gets the job done with floats and ints. The log finds to what power of 2 n is and floor rounds it down so that the resulting divisor is the nearest power of 2 below n. I've also tried this:
def justify(n):
return n / int( '1'.ljust( len( bin(n) ) - 2, '0' ), 2 )
This one just take the length of the binary representation and pads zeroes based on that. Of course, that only works with ints. I was wondering if there is any way to perform this operation with bitwise operations. It seems like the binary would lend itself well to the power of 2 operation. At minimum, I would like to see a way to replace 2 ** floor( log(n,2) )
with something bitwise. Extra points if it can handle floats, but I understand that's more complicated.