Search code examples
pythonmathalgebra

How to write (+/-) in Python?


I'm new to Python and I have below this formula and I faced (+/-) before the square root. How could I write it in Python?

Factorization Formula


Solution

  • One way or another, you'll have to build two expressions, one with the plus sign and the other with the minus sign. This is the most straightforward way:

    from math import sqrt
    
    x1 = (-b + sqrt(b*b - 4*a*c)) / 2.0
    x2 = (-b - sqrt(b*b - 4*a*c)) / 2.0
    

    Of course you should calculate the value of b*b - 4*a*c only once and store it in a variable, and check if it's negative before proceeding (to avoid an error when trying to take the square root of a negative number), but those details are left as an exercise for the reader.