Search code examples
pythonmathsquare-rootsqrt

Difference between **(1/2), math.sqrt and cmath.sqrt?


What is the difference between x**(1/2) , math.sqrt() and cmath.sqrt()?

Why does cmath.sqrt() get complex roots of a quadratic right alone? Should I use that for my square roots exclusively? What do they do in the background differently?


Solution

  • If you look at the documentation for cmath and math respectively, you will find that:

    1. cmath "provides access to mathematical functions for complex numbers"
    2. math "functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers."
    3. The (**) operator maps to the pow function, with the important difference that pow converts its arguments to float.

    Hence, you may see different results with the three functions for same arguments, as demonstrated here. Please note that if the expression has a real solution, there will be no difference between the value returned by math.sqrt and the real part of the value returned by cmath.sqrt. However, you will get an error with math.sqrt if no real solution is available.

    Edit: As @jermenkoo points out, there will be a difference in the value returned by (**) between Python 2 and 3 due to the difference in how the / operator works. However, if you directly use 0.5 instead of 1/2, that should not cause issues.