Maths and mapping


Hi everyone. Where might I find information about mathematic functions and methods, or more broadly, dealing with numeric values, in Sonic Pi?

For example, I’m looking to map incoming MIDI data (i.e., 0–127) onto a new range. In Max, I would do this by using the scale object. Additionally, how might I go about dealing with conversion, e.g., from float to integer?



Are you looking to do a linear mapping? If so, there’s no supported functionality built-into Sonic Pi at this stage (although this is planned for a future version). For now, this is how you might calculate a linear range mapping:

           (out_max - out_min) (val - in_min)
   f (x) = --------------------------------  + out_min
                    in_max - in_min

With respect to converting from float to integer - in which context are you trying to do this? You typically shouldn’t need to worry if something’s a float or an int…


sorry to revive this thread, but I’m looking for the same solution.

i’ve used processing and there’s a map function to take the range you give and spread it over the range you want…

I’m not sure how to do this in sonic Pi even with the function you’ve shown here…


You can define a function to do it

   define :rMap do |rIn, rOut, v|
      dOut = rOut[1] - rOut[0]
      dIn = rIn[1] - rIn[0]
      dOut / dIn * (v - rIn[0]) + rOut[0]

    rIn =  [0.0, 2.5]
    rOut = [10, 20.0]

    puts rMap(rIn, rOut, 0)
    puts rMap(rIn, rOut, 1)
    puts rMap(rIn, rOut, 2.5)