I recently discovered that x**.5
and math.sqrt(x)
do not always produce the same result in Python:
Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 >>> 8885558**.5 - math.sqrt(8885558) -4.5474735088646412e-13
Checking all integers below 10**7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers.
So the question is, which method is more accurate?
sqrt() is used to return the square root of a number.
The Math. sqrt() method returns the square root of a number.
The math. sqrt() method returns the square root of a number. Note: The number must be greater than or equal to 0.
The sqrt function returns a double value (for natural reasons which I'm sure that you understand). This value is typically represented in 8 bytes, in floating-point format (as specified by the standard). It doesn't have decimal digits in the way that you see them.
Neither one is more accurate, they both diverge from the actual answer in equal parts:
>>> (8885558**0.5)**2 8885557.9999999981 >>> sqrt(8885558)**2 8885558.0000000019 >>> 2**1023.99999999999 1.7976931348498497e+308 >>> (sqrt(2**1023.99999999999))**2 1.7976931348498495e+308 >>> ((2**1023.99999999999)**0.5)**2 1.7976931348498499e+308 >>> ((2**1023.99999999999)**0.5)**2 - 2**1023.99999999999 1.9958403095347198e+292 >>> (sqrt(2**1023.99999999999))**2 - 2**1023.99999999999 -1.9958403095347198e+292
http://mail.python.org/pipermail/python-list/2003-November/238546.html
The math module wraps the platform C library math functions of the same names;
math.pow()
is most useful if you need (or just want) high compatibility with C extensions calling C'spow()
.
__builtin__.pow()
is the implementation of Python's infix**
operator, and deals with complex numbers, unbounded integer powers, and modular exponentiation too (the Cpow()
doesn't handle any of those).
** is more complete. math.sqrt
is probably just the C implementation of sqrt which is probably related to pow
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With