Search code examples
sympyfactorization

Calculation where output is square polynomial plus remainder


My son is learning how to calculate the formula for a parabola using a directrix and focus point on his Khan Academy course. (a,b) is the focus point, k is the parameter for the directrix as y=k. I wanted to show him a simple way to check his results using Sympy; programming helps hugely in solidifying internal algorithms. Step 1 is clearly to set the equation out.

Parabola = Eq(sqrt((y-k)**2),sqrt((x-a)**2+(y-b)**2))

I first solved this for y, intending then to show how to substitute values and derive the equation, thus:

Y = solve(Parabola,y)

This was in a reasonable form, having collected the 1/(2b-2k) to the outside. Next, I substituted the value of the focus and directrix into the equation, obtaining the equation y= 1/6*(x**2+16*x+49), which is correct.

He needed next to resolve this in a form (x+c1)(x+c2)+remainder. There does not seem to be a direct way to factor from the equation above into this form, at least not from an hour searching the docs.

Answer = Y[0].subs({a:-8,b:-1,k:-4})
factor(Answer,deep=True)

Of course I understand how to reduce to a square factorization plus remainder; my question is solely whether this is possible in sympy and, if so, how?

A second, perhaps trivial, question is why Sympy returns some factorizations as (constant - x) where (x -constant) is preferred: is there a way of specifying the form?

Thanks for any help, on behalf of my son, to whom I am showing the wonders of Sympy.


Solution

  • The process is usually called "completing the square". It is not implemented as a single SymPy method, but one can use the SymPy equation solver to find the coefficients of such a form of the polynomial:

    >>> var('A B C')
    >>> solve(Eq(Answer, A*(x-B)**2 + C), [A, B, C])
    [(1/6, -8, -5/2)]
    

    So the parabola vertex is at (8, -5/2), and the polynomial can be written as 1/6*(x+8)**2 - 5/2