Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more accurate, x**.5 or math.sqrt(x)?

Tags:

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?

like image 728
Ben Blank Avatar asked May 08 '09 23:05

Ben Blank


People also ask

Why do we use Math sqrt X )?

sqrt() is used to return the square root of a number.

What does Math sqrt do?

The Math. sqrt() method returns the square root of a number.

What does Math sqrt mean in Python?

The math. sqrt() method returns the square root of a number. Note: The number must be greater than or equal to 0.

Does Math sqrt return a double?

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.


1 Answers

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's pow().

__builtin__.pow() is the implementation of Python's infix ** operator, and deals with complex numbers, unbounded integer powers, and modular exponentiation too (the C pow() 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.

like image 185
Unknown Avatar answered Oct 06 '22 00:10

Unknown