23

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?

5
  • Can you explain what you mean by "error rate"? Commented May 8, 2009 at 23:41
  • The two methods of calculating a square root do not produce identical results for 10,103 numbers below 10**7. (Or about 0.1%)
    – Ben Blank
    Commented May 8, 2009 at 23:45
  • 2
    I see, that's what I suspected you might have meant. You will probably find that when there is a difference between the two calculation methods, the difference will be in the least significant one or possibly two bits of the floating point representation. This is considered normal and is a consequence of the different algorithms used to compute the results. Commented May 8, 2009 at 23:59
  • 3
    Reading through the answers so far, nobody has talked about the actual algorithm being implemented for each. If anyone knows I'd be interested to read about them.
    – saffsd
    Commented May 9, 2009 at 0:54
  • 1
    @saffsd, it is likely they both use a convergent iterative series like Newton's method. If they pick different starting points, one left of the x-intercept, one to the right of the x-intercept, then that may explain the difference.
    – Unknown
    Commented May 12, 2009 at 21:11

9 Answers 9

26

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.

3
  • 9
    sqrt is one of the basic operations defined by IEEE 754. It should be implemented directly, not as a call to pow, and as a basic operation it should have correct rounding (which usual implementations of pow do not have, not by a long shot). Commented Jan 15, 2010 at 9:51
  • 5
    Computing the respective squares of (8885558**0.5) and sqrt(8885558) in floating-point at the same precision as the power/square root and expecting that computation to tell anything about which result is more accurate is naive. Concluding that “they both diverge from the actual answer in equal parts” is laughable: their squares computed in floating-point differ from 8885558.0 each by 1ULP. Commented Sep 23, 2013 at 23:20
  • The link has moved: mail.python.org/pipermail/python-list/2003-November/205890.html Commented Jul 27, 2014 at 13:35
11

Both the pow function and the math.sqrt() function can calculate results that are more accurate than what the default float type can store. I think the errors you're seeing is a result of the limitations of floating point math rather than inaccuracies of the functions. Also, since when is a difference of ~10^(-13) a problem when taking the square root of a 7 digit number? Even the most accurate physics calculations seldom requires that many significant digits...

Another reason to use math.sqrt() is that it's easier to read and understand, which generally is a good reason to do things a certain way.

8
  • The answer to this question would seem to contradict your comment about speed: stackoverflow.com/questions/327002/…
    – Ben Blank
    Commented May 8, 2009 at 23:43
  • A friend of mine actually benchmarked this earlier today, and concluded that math.sqrt() was faster. This was in the context of a project euler calculation. I trusted his word without checking his method, so that assertion might be incorrect. Still, it seems wildly unlikely that math.sqrt() would be slower. If that was the case, why didn't they simply implement it in turns of pow()?
    – Emil H
    Commented May 8, 2009 at 23:49
  • "in terms of pow()"... I'm a bit tired. :)
    – Emil H
    Commented May 8, 2009 at 23:51
  • 1
    I'll admit that I don't have a case on-hand where that level of accuracy is significant — I'm thinking more in terms of best practices. My main concern, actually, is Project Euler and the increasingly-large numbers which it's throwing at me. ;-)
    – Ben Blank
    Commented May 9, 2009 at 0:08
  • 1
    That's a great reason. PE is totally addictive. :D Take a look at decimal: docs.python.org/library/decimal.html It provides all the accuracy you'll ever need.
    – Emil H
    Commented May 9, 2009 at 0:12
7

Use decimal to find more precise square roots:

>>> import decimal
>>> decimal.getcontext().prec = 60
>>> decimal.Decimal(8885558).sqrt()
Decimal("2980.86531061032678789963529280900544861029083861907705317042")
4

Any time you are given a choice between two functions which are built into a language, the more specific function will almost always be equal to or better than the generic one (since if it was worse, the coders would've just implemented it in terms of the generic function). Sqrt is more specific than generic exponentiation so you can expect it's a better choice. And it is, at least in terms of speed. In terms of accuracy, you aren't dealing with enough precision in your numbers to be able to tell.

Note: To clarify, sqrt is faster in Python 3.0. It's slower in older versions of Python. See J.F. Sebastians measurements at Which is faster in Python: x**.5 or math.sqrt(x)? .

3
  • Can you clarify that last sentence for me?
    – Ben Blank
    Commented May 8, 2009 at 23:47
  • Your point about speed is incorrect. **0.5 is actually faster than sqrt.
    – Unknown
    Commented May 9, 2009 at 2:27
  • @Unknown I'm not so sure about that. import timeit; from random import random as unit; from math import sqrt; from operator import pow as pow_; assert timeit.timeit(lambda: sqrt(unit())) < timeit.timeit(lambda: pow_(unit(), 0.5)) reliably passes for me on Python 3.9.10. This answer and the answer it links to are correct. (However, it's worth noting that the math function chokes on negative numbers.) Commented Jan 26, 2023 at 15:27
3

This has to be some kind of platform-specific thing because I get different results:

Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
>>> 8885558**.5 - math.sqrt(8885558)
0.0

What version of python are you using and what OS?

My guess is that it has something to do with promotion and casting. In other words, since you're doing 8885558**.5, 8885558 has to be promoted to a float. All this is handled differently depending on the operating system, processor, and version of Python. Welcome to the wonderful world of floating point arithmetic. :-)

3
  • "Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32"
    – Ben Blank
    Commented May 8, 2009 at 23:52
  • Interesting. Perhaps it's a 32 bit vs 64 bit issue of some kind? Me and the other person who got different results are both using a 64-bit OS. Or it could be a BSD thing. I'm using Mac OS X. Commented May 9, 2009 at 0:00
  • I get 0.0 on 32-bit Linux as well (Python 2.5.2).
    – David Z
    Commented May 9, 2009 at 0:09
3

I got the same issue with you on Win XP Python 2.5.1, while I don't on 32-bit Gentoo Python 2.5.4. It's a matter of C library implementation.

Now, on Win, math.sqrt(8885558)**2 gives 8885558.0000000019, while (8885558**.5)**2 gives 8885557.9999999981, which seem to amount to the same epsilon.

I say that one cannot really say which one is the "better" option.

1

I don't get the same behavior. Perhaps the error is platform specific? On amd64 I get this:

Python 2.5.2 (r252:60911, Mar 10 2008, 15:14:55) 
[GCC 3.3.5 (propolice)] on openbsd4
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.sqrt(8885558) - (8885558**.5)
0.0
>>> (8885558**.5) - math.sqrt(8885558)
0.0
2
  • I was afraid that might be the case — I read somewhere that math.sqrt is passed directly to the C implementation, but I can't find the reference right now.
    – Ben Blank
    Commented May 8, 2009 at 23:50
  • Ben: I can't find it documented, but it's true for Python 2.5 at least: tinyurl.com/omvudo
    – Ken
    Commented May 13, 2009 at 20:31
1

In theory math.sqrt should have a higher precision then math.pow. See Newton's method to compute square roots [0]. However the limitation in the number of decimal digits of the python float (or the C double) will probably mask the difference.

[0] http://en.wikipedia.org/wiki/Integer_square_root

0

I performed the same test and got the same results, 10103 differences out of 10000000. This was using Python 2.7 in Windows.

The difference is one of rounding. I believe when the two results differ, it is only one ULP which is the smallest possible difference for a float. The true answer lies between the two, but a float doesn't have the ability to represent it exactly and it must be rounded.

As noted in another answer, the decimal module can be used to get better accuracy than a float. I utilized this to get a better idea of the true error, and in all cases the sqrt was closer than the **0.5. Although not by much!

>>> s1 = sqrt(8885558)
>>> s2 = 8885558**0.5
>>> s3 = decimal.Decimal(8885558).sqrt()
>>> s1, s2, s3
(2980.865310610327, 2980.8653106103266, Decimal('2980.865310610326787899635293'))
>>> s3 - decimal.Decimal(s1)
Decimal('-2.268290468226740188598632812E-13')
>>> s3 - decimal.Decimal(s2)
Decimal('2.2791830406379010009765625E-13')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.