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:
Your case: 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; |
||||
|
|
The range
So you first add |
|||
|
|
|
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. In summary:
|
|||
|
|
|
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 Done! Example: 0.5 will go: (0.5 + 1) * 127.5 = 191.25 -0.5 will go: (-0.5 + 1) * 127.5 = 63.75 |
|||
|
|
|
Lets say Since we want to do a linear interpolation we can look into the equation of form
With above two points, we can solve for Note this method works for other types of equations too. e.g If you want a exponential or quadratic interpolation. |
|||||
|
