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

Óscar López
  • 232,561
  • 37
  • 312
  • 386

2 Answers2

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
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