# Taking elements in solve and multiplying to a polynomial

So I want a function that solves a system of two equations and the move those numerical results to polynomials f and g.

def PolynomialCoefficient(fcn1, fcn2):
var ('a b')
eqn1 = 2*a + 2*b == 0
eqn2 = 3*a - b == 1
List = solve([eqn1, eqn2], a, b)


Now I want to move this to a*f(x)+b*g(x) without hitting solve each time and manually typing what a and b are. For example, PolynomialCoefficient(x, y) should output 1/4 x - 1/4 y.

The issue is len(List) outputs 1. If it was length 2 with a in first slot and b in 2nd slot, I could do

    Poly = List[0]*fcn1 + List[1]*fcn2
return Poly


Any ideas on how to move a and b?

edit retag close merge delete

Sort by ยป oldest newest most voted

The solve function has an optional argument solution_dict.

Using it, solutions are returned as dictionaries, which makes it easier to access the solved values of each unknown.

Here is a way to use that in the function from the question.

def polynomial_coefficient(fcn1, fcn2):
a, b = SR.var('a, b')
eqn1 = 2*a + 2*b == 0
eqn2 = 3*a - b == 1
sol = solve([eqn1, eqn2], a, b, solution_dict=True)[0]
return sol[a]*fcn1 + sol[b]*fcn2

more

Great thanks

( 2021-03-20 05:19:01 +0200 )edit

Your List is a list of solutions with respect to a,b. If you want just one solution you can re-define it as

List=solve([eqn1,eqn2],a,b)[0]


and then proceed as in your code; or if you want to get Poly as a list of polynomials (one for each solution), you can define it as

Poly=[ List[0]*fcn1+List[1]*fcn2 for List in solve([eqn1,eqn2],a,b) ]

more

( 2021-03-20 05:19:10 +0200 )edit