1

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

8
  • 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. Commented 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 - Commented Aug 3, 2019 at 7:37
  • With array you can Commented Aug 3, 2019 at 7:38
  • 1
    Are 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?)? Commented Aug 3, 2019 at 7:39
  • Do you want to print it or evaluate it? Commented Aug 3, 2019 at 7:39

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

11 Comments

Why not with list ?
@deoncagadoes what do you mean?
x[0] = formula; x[1] = formula2;
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]].
D = b*b - 4*a*c; if D < 0: error; [-b + sign * sqrt(D) / 2 for sign in [1, -1]]
|
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.

Comments