 <p>The h values need to be adjusted for the three cases prior to calculating the cos values dependent on them. i.e.:</p> <pre><code> if(h&lt;(2.0f*pi/3.0f)){ y = in*( 1.0f + (s*cos(h) / cos(pi/3.0f-h)) ); b = x; r = y; g = z; }else if(h&lt;(4.0f*pi/3.0f)){//&amp;&amp;2pi/3&lt;=h h -= 2*pi/3; y = in*( 1.0f + (s*cos(h) / cos(pi/3.0f-h)) ); r = x; g = y; b = z; }else{ //less than 2pi &amp;&amp; 4pi/3&lt;=h h -= 4*pi/3; y = in*( 1.0f + (s*cos(h) / cos(pi/3.0f-h)) ); g = x; b = y; r = z; } </code></pre> <p>You will also need to make sure that none of the rr,gg,bb values end up outside the 0..255 interval:</p> <pre><code>if (rr &lt; 0) rr = 0; if (rr &gt; 255) rr = 255; </code></pre> <p>... etc</p>