"normalizing" a value

MRAB python at mrabarnett.plus.com
Wed Jul 1 20:30:45 EDT 2015


On 2015-07-02 01:12, bvdp wrote:
> Not sure what this is called (and I'm sure it's not normalize). Perhaps "scaling"?
>
> Anyway, I need to convert various values ranging from around -50 to 50 to an 0 to 12 range (this is part of a MIDI music program). I have a number of places where I do:
>
>     while x < 0: x += 12
>     while x >= 12: x -= 12
>
> Okay, that works. Just wondering if there is an easier (or faster) way to accomplish this.
>
That's called "modular arithmetic". Use the modulo operator, '%':

     x = x % 12

or just:

     x %= 12




More information about the Python-list mailing list