quantization

for music input quantization (to 16th, 32th notes)

by jmchen

HTML

number   <input id='number' value=1.33 style='width:6em'></input>
<br/><br/>
base   <input id='base' value=8 style='width:6em'></input>
<br/><br/>
Quantization: <p id='result'></p>

JavaScript

$('#number').on('keyup', function (e) {
    if (e.keyCode === 13) {
        number = $('#number').val();
    }
    $('#result').text(quantize(number,base));
});
$('#base').on('keyup', function (e) {
    if (e.keyCode === 13) {
        base = $('#base').val();
    }
});


function quantize (the_number,base) {  // 3.55, 8
    var whole = Math.floor (the_number);  // 3
    var fraction = the_number - whole;    // 0.55
    return (whole + quantizeFraction(fraction,base));
}

function quantizeFraction (number, base) {
    // number = c1*base^-1 + c2*base^-2 + ....

    // number*base = c1*base^0 + c2*base^-1 + ...
    var intPart = Math.floor (number * base); // c1
    var fraction = number - intPart/base; // c2*base^-2 + ... 
    
    // 0.c1 or 0.(c1+1)?
    // fraction*base = c2*base^-1 + ...
    // fraction*base*base = c2*base^0 + ....
    // if (c2 >= base/2) 0.(c1+1)
    // else              0.(c1)
    if (Math.floor(fraction * base * base) >= base/2)
        intPart += 1;
    return (intPart/base);
}

var number = 1.33;
var base = 8;