Reputation:
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?
Upvotes: 1
Views: 317
Reputation: 236124
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.
Upvotes: 4
Reputation: 29985
This is essentially two formulas represented in one. There is no way to do that in Python. Just use two separate formulas. One with plus one with minus.
Upvotes: 2