bennyguitar / Colours

A beautiful set of predefined colors and a set of color methods to make your iOS/OSX development life easier.
MIT License
3.09k stars 300 forks source link

distanceFromColor returns NAN #45

Open dxclancy opened 8 years ago

dxclancy commented 8 years ago

Thanks for you library!

For this line in distanceFromColor deltaH is NAN, which causes the result to be NAN.

CGFloat deltaH = sqrt(pow((A1 - A2), 2.0) + pow((B1 - B2), 2.0) - pow(deltaC, 2.0));

These were values the values in the debugger - I've had other combos trigger this.

(lldb) po self
UIDeviceRGBColorSpace 0.411765 0.176471 0.894118 1
(lldb) po color
UIDeviceRGBColorSpace 0.0655637 0.077451 0.0641544 1 

This is because the sqrt is being taken from is a very small negative number. Likely because of float/double precision issues?

In this case, i am setting deltaH to zero. Perhaps it would be more appropriate to take the sqrt of abs? Either way will result in a very small number later on when this result is used.

    CGFloat varA = pow((A1-A2), 2.0);
    CGFloat varB = pow((B1-B2), 2.0);
    CGFloat varC = pow(deltaC, 2.0);
    CGFloat varD = varA + varB - varC;
    CGFloat deltaH = sqrt(varD);   // varD negative
    if (isnan(deltaH))
    {
        deltaH = 0;
        NSLog(@"NAN");
    }