8000 gh-106498: Fix an extreme case in `colorsys.rgb_to_hls` by gaogaotiantian · Pull Request #106530 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-106498: Fix an extreme case in colorsys.rgb_to_hls #106530

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add fix and regression test for near white color
  • Loading branch information
gaogaotiantian committed Jul 7, 2023
commit 7b106c397dfa91b32b2c57718e6d37d012768971
8 changes: 7 additions & 1 deletion Lib/colorsys.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,13 @@ def rgb_to_hls(r, g, b):
sumc = (maxc+minc)
rangec = (maxc-minc)
l = sumc/2.0
if minc == maxc:
# gh-106498
# Due to a degree of float precision error, it's possible that maxc != minc
# but maxc + minc == 2.0. Which will make (2.0 - sumc) zero, causing the
# ZeroDivisionError.
# e.g. colorsys.rgb_to_hls(1, 1, 0.9999999999999999)
# In this case, it's an extreme near white color so we can just return white
if minc == maxc or sumc == 2.0:
return 0.0, l, 0.0
if l <= 0.5:
s = rangec / sumc
Expand Down
6 changes: 6 additions & 0 deletions Lib/test/test_colorsys.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ def test_hls_values(self):
self.assertTripleEqual(hls, colorsys.rgb_to_hls(*rgb))
self.assertTripleEqual(rgb, colorsys.hls_to_rgb(*hls))

def test_hls_corner_case(self):
try:
colorsys.rgb_to_hls(1, 1, 0.9999999999999999)
except Exception:
self.fail("rgb_to_hls(1, 1, 0.9999999999999999) raised an exception!")

def test_yiq_roundtrip(self):
for r in frange(0.0, 1.0, 0.2):
for g in frange(0.0, 1.0, 0.2):
Expand Down
0