I'm doing terrain generation and I have a perlin library that is giving me random numbers between -1 and +1. I want to convert this to the scale of 0-255. What is the proper way to do this?
Base formula is:
Result := ((Input - InputLow) / (InputHigh - InputLow)) * (OutputHigh - OutputLow) + OutputLow;
Result := ((Input - -1) / (1 - -1) * (255 - 0) + 0;
From here you can optimize the conversion if your coefficients are static, but compiler will probably do it by itself as well.
Result := ((Input - -1) / 2) * 255 + 0;
Result := Input * 127.5 + 127.5;
Through the power of scaling and bias.
From your value, subtract the minimum value of your range. That will give you a value in the range [0..2].
Divide that by the width of the source range, giving you a value in the range [0..1].
Multiply that by the width of the target range, giving you a value in the range [0..255].
Add the base of the target range to get a value in the target range, which for this case is the same as the previous step.
(v - (-1.0)) v' = 0 + ---------------- * (255 - 0) (1.0 - (-1.0))
Translate the input range so we get the min to zero by adding 1 (the negative value of the min input) -1 .. 1 -> 0 .. 2
As the output range starts with zero, do nothing for that.
Scale the new input range so it fits the output range, this is easy as they now both starts at zero: multiply the value by 255/2 0..2 * 2/255 -> 0..255
0.5 will go: (0.5 + 1) * 127.5 = 191.25 -0.5 will go: (-0.5 + 1) * 127.5 = 63.75
x is original input and
y is expected output.
We have at least two points
Since we want to do a linear interpolation we can look into the equation of form
y = m*x + c
With above two points, we can solve for
Once that is done, you get the transform equation.
Note this method works for other types of equations too. e.g If you want a exponential or quadratic interpolation.