Need algorithm that will map floats to RGB

I am looking for an algorithm that will map a range of floats to RGB. My google skills are apparently lacking as I can’t find exactly what I need. Here is what I want to do:

I have a range of floats: fmin <= f <= fmax
I want to map f to RGB such that

fmin = RGB(0,0,0)
fmax = RGB(255,255,255)

For example see this image:

Any suggestions? Pointers to reading info? etc?

In what? GLSL, C?

I don’t think Google is what you need, it’s just a C book, or a simple mathematics course - possibly just a cup of tea and a piece of paper.

Anyway, hoping I’m not doing your homework…

Work out the range. Take each float and subtract the min, then divide by the range. That gives you the position of the float in a 0-1 range. Set your color so that red, green and blue are that position, and alpha is 1.0. Scale it to 255 if you need to - OpenGL is 0-1.0.


If you don’t want to interpolate between colors from black to white (grayscale) but an arbitrary spectrum, you can compute the “range position” as Bruce explained and then use it as a texture coordinate in a 1D texture that represents the wanted color spectrum.

This is pretty standard fare in scientific visualization. The OpenDX package for instance uses the AutoColor module to do this. You can change it, but in the default colormap it uses “the minimum data value is blue, the maximum data value is red, and data values between are blue to red through cyan, green, and yellow” (example here). There’s your 1D texture.

Of course you can use whatever color ramp you want.