[Tutor] Associate decimal values with an integer range

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Apr 29 17:27:50 CEST 2013


On 29 April 2013 15:28, sparkle Plenty <sparkle.plenty12481632 at gmail.com> wrote:
> Hi, I need some hints on where to start solving this problem.
> I have to interpret a one-byte floating point number as a range between 0
> and 240.  This is for a gui that controls an amplifier.  I am getting a
> value such as 0.8367 from a fader control, and my Python is interpreting it
> as either a 0 or 1.  I need to define this number to Python as an integer
> value between 0 and 240.  I know that in hex I have the potential for
> numbers from 0 to 255 within my one byte of available space, and the value
> will be sent from gui to amp and back as a packed one-byte number.  I have
> looked at the math module and so far, I am still stuck.

You need to define the range of values that you will accept. If you
want the floating point numbers to map linearly to integers you can
then use:

byte = int(241 * float_value / max_float_value)

This will give a value between 0 and 240 inclusive for any positive
float_value that is less than max_float_value. The integer values will
be approximately proportional to the float values.

You may also want to check for overflow:

byte = min(byte, 240)

> Alas, business calc was a long time ago, and I never studied logarithms.  I
> expect the answer would be easier to find if I had more math.

Logarithms would be useful for a different (non-linear) type of
scaling. I can't tell you whether or not you want logarithmic scaling
since I'm not sure what the byte integer is needed for. If you did
want to use logarithmic scaling then you could do something like:

byte = int((241 / math.log(2)) * math.log(1 + float_value / max_float_value))


Oscar


More information about the Tutor mailing list