[Python-checkins] [3.11] gh-106498: Revert incorrect colorsys.rgb_to_hls change (GH-106627) (#106633)

terryjreedy webhook-mailer at python.org
Tue Jul 11 11:48:04 EDT 2023


https://github.com/python/cpython/commit/da15b12d8d7f4fec89d4e56f61799048b0590c95
commit: da15b12d8d7f4fec89d4e56f61799048b0590c95
branch: 3.11
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: terryjreedy <tjreedy at udel.edu>
date: 2023-07-11T15:48:00Z
summary:

[3.11] gh-106498: Revert incorrect colorsys.rgb_to_hls change (GH-106627) (#106633)

gh-106498: Revert incorrect colorsys.rgb_to_hls change (GH-106627)

gh-86618 assumed a-b-c = a-(b+c) = a-d where d = b+d.
For floats 2.0, 1.0, and 0.9999999999999999, this assumption
is false.  The net change of 1.1102230246251565e-16 to 0.0
results in division by 0.  Revert the replacement.  Add test.
(cherry picked from commit a2d54d4e8ab12f967a220be88bde8ac8227c5ab3)

Co-authored-by: Terry Jan Reedy <tjreedy at udel.edu>

files:
A Misc/NEWS.d/next/Library/2023-07-11-09-25-40.gh-issue-106530.VgXrMx.rst
M Lib/colorsys.py
M Lib/test/test_colorsys.py

diff --git a/Lib/colorsys.py b/Lib/colorsys.py
index 9bdc83e377260..bc897bd0f9929 100644
--- a/Lib/colorsys.py
+++ b/Lib/colorsys.py
@@ -83,7 +83,7 @@ def rgb_to_hls(r, g, b):
     if l <= 0.5:
         s = rangec / sumc
     else:
-        s = rangec / (2.0-sumc)
+        s = rangec / (2.0-maxc-minc)  # Not always 2.0-sumc: gh-106498.
     rc = (maxc-r) / rangec
     gc = (maxc-g) / rangec
     bc = (maxc-b) / rangec
diff --git a/Lib/test/test_colorsys.py b/Lib/test/test_colorsys.py
index a24e3adcb4b84..74d76294b0b4d 100644
--- a/Lib/test/test_colorsys.py
+++ b/Lib/test/test_colorsys.py
@@ -69,6 +69,16 @@ def test_hls_values(self):
             self.assertTripleEqual(hls, colorsys.rgb_to_hls(*rgb))
             self.assertTripleEqual(rgb, colorsys.hls_to_rgb(*hls))
 
+    def test_hls_nearwhite(self):  # gh-106498
+        values = (
+            # rgb, hls: these do not work in reverse
+            ((0.9999999999999999, 1, 1), (0.5, 1.0, 1.0)),
+            ((1, 0.9999999999999999, 0.9999999999999999), (0.0, 1.0, 1.0)),
+        )
+        for rgb, hls in values:
+            self.assertTripleEqual(hls, colorsys.rgb_to_hls(*rgb))
+            self.assertTripleEqual((1.0, 1.0, 1.0), colorsys.hls_to_rgb(*hls))
+
     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):
diff --git a/Misc/NEWS.d/next/Library/2023-07-11-09-25-40.gh-issue-106530.VgXrMx.rst b/Misc/NEWS.d/next/Library/2023-07-11-09-25-40.gh-issue-106530.VgXrMx.rst
new file mode 100644
index 0000000000000..09fc647cc01d2
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2023-07-11-09-25-40.gh-issue-106530.VgXrMx.rst
@@ -0,0 +1,2 @@
+Revert a change to :func:`colorsys.rgb_to_hls` that caused division by zero
+for certain almost-white inputs.  Patch by Terry Jan Reedy.



More information about the Python-checkins mailing list