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?
Asked
Active
Viewed 233 times
1
-
out of the box, you can't. Computer languages and mathematical equations don't always one-to-one. There are two "values/answers" packed in 1 expression here. – Paritosh Singh Aug 03 '19 at 07:37
-
This equation is meant to calculate two solutions, you need to find the first using + and the second using - – marc Aug 03 '19 at 07:37
-
With array you can – deon cagadoes Aug 03 '19 at 07:38
-
1Are you asking what ± means (not a programming question) or how to write corresponding code in Python (in which case, where exactly are you stuck? what have you tried?)? – melpomene Aug 03 '19 at 07:39
-
Do you want to print it or evaluate it? – bereal Aug 03 '19 at 07:39
-
Check this https://stackoverflow.com/q/27872250/8966274 – Bidhan Majhi Aug 03 '19 at 07:39
-
@melpomene I stuck in how to write this (±) in Python? – Aug 03 '19 at 07:43
-
@bereal I need to program it in Python – Aug 03 '19 at 07:44
2 Answers
4
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.

Óscar López
- 232,561
- 37
- 312
- 386
-
-
-
-
2That doesn't mean you have to write the same expression twice. You could e.g. `[-b + sign * sqrt(b*b - 4*a*c)) / 2 for sign in [1, -1]]`. – melpomene Aug 03 '19 at 07:42
-
-
@melpomene and more importantly, how do you check if the result is an imaginary number? – Óscar López Aug 03 '19 at 07:46
-
@ÓscarLópez I don't understand the question. How do you check it with your code? – melpomene Aug 03 '19 at 07:47
-
@melpomene See the comment at the end of my answer. We only need an extra variable, and with that you can check it easily. – Óscar López Aug 03 '19 at 07:48
-
-
@melpomene I'm not asking you. It's just that your proposed solution makes it hard to do the check. – Óscar López Aug 03 '19 at 07:53
-
3`D = b*b - 4*a*c; if D < 0: error; [-b + sign * sqrt(D) / 2 for sign in [1, -1]]` – melpomene Aug 03 '19 at 08:00
2
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.

Aykhan Hagverdili
- 28,141
- 6
- 41
- 93