On OS X 10.4, and probably other versions of OS X too, calls to math.log and math.sqrt that should raise ValueError instead return a NaN: Python 2.6a0 (trunk:60144, Jan 20 2008, 21:43:56) [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from math import sqrt, log >>> sqrt(-1) nan >>> log(-1) nan The problem is that OS X doesn't set errno in these cases. Attached is a quick fix for this. Note that there's already a test for this (test_exceptions in test_math.py), but this test is only run in verbose mode. See also issue #871657.
On OSX 10.5 this behavior is confirmed (Python2.5 and 2.6a). This fix appears to be a good fix for python 2.6a. (Python 2.6a with patch applied) Python 2.6a0 (trunk:60977M, Feb 23 2008, 19:24:52) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from math import log,sqrt >>> sqrt(-1) Traceback (most recent call last): File "", line 1, in ValueError: math domain error >>> log(-1) Traceback (most recent call last): File "", line 1, in ValueError: math domain error david-kwasts-macbook:python-trunk davidkwast$ ./python ./Lib/test/test_math.py testAcos (__main__.MathTests) ... ok testAsin (__main__.MathTests) ... ok testAtan (__main__.MathTests) ... ok testAtan2 (__main__.MathTests) ... ok testCeil (__main__.MathTests) ... ok testConstants (__main__.MathTests) ... ok testCopysign (__main__.MathTests) ... ok testCos (__main__.MathTests) ... ok testCosh (__main__.MathTests) ... ok testDegrees (__main__.MathTests) ... ok testExp (__main__.MathTests) ... ok testFabs (__main__.MathTests) ... ok testFloor (__main__.MathTests) ... ok testFmod (__main__.MathTests) ... ok testFrexp (__main__.MathTests) ... ok testHypot (__main__.MathTests) ... ok testIsinf (__main__.MathTests) ... ok testIsnan (__main__.MathTests) ... ok testLdexp (__main__.MathTests) ... ok testLog (__main__.MathTests) ... ok testLog10 (__main__.MathTests) ... ok testModf (__main__.MathTests) ... ok testPow (__main__.MathTests) ... ok testRadians (__main__.MathTests) ... ok testSin (__main__.MathTests) ... ok testSinh (__main__.MathTests) ... ok testSqrt (__main__.MathTests) ... ok testTan (__main__.MathTests) ... ok testTanh (__main__.MathTests) ... ok test_exceptions (__main__.MathTests) ... ok test_trunc (__main__.MathTests) ... ok ---------------------------------------------------------------------- Ran 31 tests in 0.011s OK
Thanks for the confirmation, David! The work in the trunk-math branch should also fix this, in a rather better fashion (i.e., without per-platform hacks). This issue should probably be revisited after it's decided whether to merge trunk-math into the trunk before 2.6.