[3.8] bpo-39871: Fix possible SystemError in atan2, copysign and remainder (GH-18806) (GH-18989)

In math_2(), the first PyFloat_AsDouble() call should be checked
for failure before the second call.

Co-authored-by: Mark Dickinson <dickinsm@gmail.com>.
(cherry picked from commit 5208b4b37953a406db0ed6a9db545c2948dde989)

Co-authored-by: Zackery Spytz <zspytz@gmail.com>
diff --git a/Lib/test/test_math.py b/Lib/test/test_math.py
index 6abaeea..4a1ba83 100644
--- a/Lib/test/test_math.py
+++ b/Lib/test/test_math.py
@@ -1878,6 +1878,22 @@
             self.assertIs(type(comb(IntSubclass(5), IntSubclass(k))), int)
             self.assertIs(type(comb(MyIndexable(5), MyIndexable(k))), int)
 
+    def test_issue39871(self):
+        # A SystemError should not be raised if the first arg to atan2(),
+        # copysign(), or remainder() cannot be converted to a float.
+        class F:
+            def __float__(self):
+                self.converted = True
+                1/0
+        for func in math.atan2, math.copysign, math.remainder:
+            y = F()
+            with self.assertRaises(TypeError):
+                func("not a number", y)
+
+            # There should not have been any attempt to convert the second
+            # argument to a float.
+            self.assertFalse(getattr(y, "converted", False))
+
     # Custom assertions.
 
     def assertIsNaN(self, value):