Output the Visible Spectrum in RGB
Inspired by http://www.physics.sfasu.edu/astro/color/spectra.html
Light with wavelength between ~380 and 780 nanometers is considered to be within the visible spectrum. One can approximate the colors of the visible spectrum in RGB space by linearly-interpolating the wavelength at specific ranges. The ranges and corresponding formula for a wavelength wl
are given below, assuming each color value is a float between 0 and 1:
- [380-440):
r = (440 - wl) / (440 - 380), g = 0, b = 1
- [440-490):
r = 0, g = (wl - 440) / (490 - 440), b = 1
- [490-510):
r = 0, g = 1, b = (510 - wl) / (510 - 490)
- [510-580):
r = (wl - 510) / (580 - 510), g = 1, b = 0
- [580-645):
r = 1, g = (645 - wl) / (645 - 580), b = 0
- [645-780):
r = 1, g = 0, b = 0
Note that in this system, the interpolation formula is cyclic with the color components, and changes sign with respect to the range maximum or minimum.
The challenge
Given an integer wavelength between 380 and 780, output the RGB value using the above interpolations.
Output may be a list of floats in [0-1] or integers between [0,255] in the format (r,g,b), or a valid RGB hex code.
This is code golf, so the shortest code in bytes wins!
Test cases
Rounding errors to within 0.01 in float format or to within 1 in integer format are acceptable.
wl=400 --> (0.29, 0.0, 0.65) or (73,0,165) or #4900A5
wl=530 --> (0.28, 1.0, 0.0) or (72,255,0) or #48FF00
wl=640 --> (1.0, 0.07, 0.0) or (255,19,0) or #FF1300
wl=750 --> (1.0, 0.0, 0.0) or (255,0,0) or #FF0000
Bonus
At extreme ranges of the visible spectrum, human perception is not as good. This can be modeled as a loss of intensity by multiplying the RGB values computed above by a factor f
for specific cutoff points:
wl
< 420: f=0.3+0.7*(wl-380)/(420-380)
wl
> 700: f=0.3+0.7*(780-wl)/(780-700)
The total (r,g,b) including the perception factor is therefore (f*r, f*g, f*b)