The function map() -- the math behind it; does it work?

This seems to be the math behind the map() function:

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

I have renamed the variables to calculate the dimmer level of a light in relation to a lux value.

dimmer_level = (lux - lux_min) * (dim_max - dim_min) / (lux_max - lux_min) + dim_max

Or as code:

int main (void)
{
    int lux_min	=    0;
    int lux_max	= 2000;
    int dim_min	=    4;
    int dim_max	=   35;

    int lux = 2000;

    int dimmer_level = (lux - lux_min) * (dim_max - dim_min) / (lux_max - lux_min) + dim_max;

    printf("dimmer value: %d\n", dimmer_level);

    return 0;
}

However, my result does not stay within out limits.

image

What did I get wrong?
Any hints appreciated.

Huh, found it!

The last value in my formula is dim_max; which should be dim_min.

The int data type will hold values from -32768 to 32767. Are any of the intermediate results of your calculations outside of that range?

See this thread >> Basic Calculation Results Wrong Value

Hi, @MaxG

The map function uses y = mx + c.
It does not just work within your input and output limits, if you enter a value outside your expected input values, the function will output a value outside your expected output values.

You may need to look at this function to use in conjunction with your values.
https://www.arduino.cc/reference/en/language/functions/math/constrain/

Tom.. :grinning: :+1: :coffee: :australia:

:slight_smile: Yes, I wanted to keep it simple and focus on the map function only.

I actually constrain the in put between min and max.

The point of having a function is that you don't have to rename variables or use the wrong data types, thus avoiding the sorts of mistakes that you made in doing so.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.