pythonpython-3.xquadratic

How to calculate coefficients, solutions etc. in quadratic function with limited inputs in Python


I have a problem. I want to calculate everything in the quadratic function. equations for reference:

ax^2 + bx + c
a(x-p)^2 + q

I made 8 possible inputs in tkinter and I want my program to try and calculate everything if possible. Otherwise to return sth like not enough data. Equations:

delta = b^2-4ac
p = -b/(2a)
p = (x1+x2)/2
q = -delta/(4a)
#if delta>0
x2 = (-b-sqrt(delta))/(2a)
x1 = (-b+sqrt(delta))/(2a)
#if delta=0
x0 = -b/(2a)
#if delta<0 no solutions
#a, b, c are the coefficients.
b = -2ap
c = p^2*a+q

Example:

Input:
p = 3
q = -9
x1 = 0.877868
a = 2

Output:
b = -12
c = 9
x2 = 5.12132
delta = 72

So, for example, I give it [x1, x2, a] and it will calculate [q, p, b, c, and delta] if possible. Is there a function that I can give all different formulas to and it will try to calculate everything? For now, my only idea is to brute force it in 'try' or with 'ifs', but I feel like it would take thousands of lines of code, so I won't do that.


Solution

  • I found out that you can use sympy's solve. This is my solution. I used Eq for defining equations and then solved them.

    def missingVariables(dictOfVariables):
        symbols = dict(a=sym('a'), b=sym('b'), c=sym('c'), p=sym('p'), q=sym('q'), x1=sym('x1'), x2=sym('x2'),
                       delta=sym('delta'))
        var = mergeDicts(symbols, dictOfVariables)
    
        deltaEQ = Eq((var['b'] ** 2 - 4 * var['a'] * var['c']), var['delta'])
        x1EQ = Eq(((-var['b'] - sqrt(var['delta'])) / (2 * var['a'])), var['x1'])
        x2EQ = Eq(((-var['b'] + sqrt(var['delta'])) / (2 * var['a'])), var['x2'])
        pEQ = Eq((-var['b']) / (2 * var['a']), var['p'])
        pEQ2 = Eq(((var['x1'] + var['x2']) / 2), var['p'])
        qEQ = Eq(((-var['delta']) / (4 * var['a'])), var['q'])
        bEQ = Eq((-2 * var['a'] * var['p']), var['b'])
        cEQ = Eq((var['a'] * var['p'] ** 2 + var['q']), var['c'])
    
        solution = solve((deltaEQ, x1EQ, x2EQ, pEQ, pEQ2, qEQ, bEQ, cEQ))
        solution = solution[0]
        new_dict = {}
        for k, v in solution.items():
            try:
                new_dict[str(k)] = round(float(v), 4)
            except TypeError:
                new_dict[str(k)] = v
        return new_dict