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?
- 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– Paritosh Singh2019-08-03 07:37:23 +00:00Commented Aug 3, 2019 at 7:37
- This equation is meant to calculate two solutions, you need to find the first using + and the second using -marc– marc2019-08-03 07:37:36 +00:00Commented Aug 3, 2019 at 7:37
- With array you candeon cagadoes– deon cagadoes2019-08-03 07:38:15 +00:00Commented Aug 3, 2019 at 7: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– melpomene2019-08-03 07:39:00 +00:00Commented Aug 3, 2019 at 7:39
- Do you want to print it or evaluate it?bereal– bereal2019-08-03 07:39:06 +00:00Commented Aug 3, 2019 at 7:39
| Show 3 more comments
2 Answers
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.
11 Comments
deon cagadoes
Why not with list ?
Óscar López
@deoncagadoes what do you mean?
deon cagadoes
x[0] = formula; x[1] = formula2;
melpomene
That 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
D = b*b - 4*a*c; if D < 0: error; [-b + sign * sqrt(D) / 2 for sign in [1, -1]] |
