How does the map() function in Processing work?

osse picture osse · Jun 16, 2013 · Viewed 16.8k times · Source

I'm taking a class which uses Processing.

I having a problem understanding the map() function.

According to it's documentation(http://www.processing.org/reference/map_.html):

Re-maps a number from one range to another.

In the first example above, the number 25 is converted from a value in the range of 0 to 100 into a value that ranges from the left edge of the window (0) to the right edge(width).

As shown in the second example, numbers outside of the range are not clamped to the minimum and maximum parameters values, because out-of-range values are often intentional and useful.

Is is similar to a random function but the range is set by the user? Also, i cant understand the explanation for the first example: it says the number is converted to a value of 0 to 100 into a value that ranges from edge to edge of the screen. im thinking why not just convert directly, the number 25 to the range of value pertaining to the screen?

Answer

user2468700 picture user2468700 · Jun 16, 2013

The map() function is a useful shortcut and you won't regret the time spent at understanding it.
This is its syntax:

variable2 = map(variable1, min1, max1, min2, max2);

The function establishes a proportion between two ranges of values:

min1 : min2 = max1 : max2

you can read it as: min1 is to min2 as max1 is to max2.
variable1 stores a value between the first range min1~max1.
variable2 gets a value between the second range min2~max2.

This is the equation the function solves for the programmer:

variable2 = min2+(max2-min2)*((variable1-min1)/(max1-min1))

This is the Java code behind the Processing map() function:

static public final float map(float value, 
                              float istart, 
                              float istop, 
                              float ostart, 
                              float ostop) {
    return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
}