Chris Snow
Chris Snow

Reputation: 24588

how to factor an equation by completing the square?

I would like to factor an equation by completing the square:

>>>> import sympy
>>>> x, c = symbols('x c')
>>>> factor(x**2 - 4*x  - 1)
x**2 - 4*x - 1

However, I was expecting to see:

(x - 2)**2 - 5

How can this be done in sympy?

Upvotes: 3

Views: 2219

Answers (2)

Chris Snow
Chris Snow

Reputation: 24588

The approach I went with in the end was:

>>> h, k, x = symbols('h k x')
>>> solve( (x-h)**2 - k  - (x**2-4*x-1), [h,k] )
[(2, 5)]
# so h = 2 and k = 5
# (x-2)**2 - 5

Source: https://minireference.com/static/tutorials/sympy_tutorial.pdf

Upvotes: 9

Bill Bell
Bill Bell

Reputation: 21643

In a circumstance like that you can get the factors using solve:

>>> solve(x**2-4*x-1)
[2 + sqrt(5), -sqrt(5) + 2]

I would not expect factor to give me the factors in the form suggested in the question. However, if you really want to 'complete the square' sympy will do the arithmetic for you (you need to know the steps) but not much more, AFAIK.

Upvotes: 3

Related Questions