if we know a + b = 4, ab = 2, we want to evaluate a^2 + b^2. Is there a common method in sympy to do the transform a^2 + b^2 = (a + b)^2 - 2ab to solve such problems. Thank you.
Maybe just this:
>>> var('a b c')
(a, b, c)
>>> solve((a+b-4,a*b-2,a**2+b**2-c))
[{a: 2 - sqrt(2), b: sqrt(2) + 2, c: 12}, {a: sqrt(2) + 2, b: 2 - sqrt(2), c: 12}]
Maybe just this:
>>> var('a b c') (a, b, c) >>> solve((a+b-4,a*b-2,a**2+b**2-c)) [{a: 2 - sqrt(2), b: sqrt(2) + 2, c: 12}, {a: sqrt(2) + 2, b: 2 - sqrt(2), c: 12}]
This is a method of solving the problem. Actually, I want to know whether this is a method to transfrom expression A in terms of expression B and C. In the problem, A is a^2 + b^2, B is a + b and C is ab. A = B^2 - 2C
I'm not sure if this is a helpful answer, but the only structured way I'm aware of to solve the problem is using ratsimpmodprime with groebner basis as answered in #19064.
from sympy import *
a, b = symbols('a b')
ratsimpmodprime(a**2+b**2, groebner([a+b-4, a*b-2]).exprs)
Maybe this is what you want:
In [28]: a, b, A, B, C = symbols('a, b, A, B, C')
In [29]: eq = [Eq(A, a**2 + b**2), Eq(B, a + b), Eq(C, a*b)]
In [30]: sol = solve(eq, [A, a, b], dict=True)
In [31]: sol = {s[A] for s in sol}
In [32]: sol
Out[32]:
⎧ 2 ⎫
⎨B - 2⋅C⎬
⎩ âŽ
Ideally we would have an eliminate function rather than needing to solve for a and b as unknowns.
Maybe this is what you want:
In [28]: a, b, A, B, C = symbols('a, b, A, B, C') In [29]: eq = [Eq(A, a**2 + b**2), Eq(B, a + b), Eq(C, a*b)] In [30]: sol = solve(eq, [A, a, b], dict=True) In [31]: sol = {s[A] for s in sol} In [32]: sol Out[32]: ⎧ 2 ⎫ ⎨B - 2â‹…C⎬ ⎩ âŽIdeally we would have an
eliminatefunction rather than needing to solve foraandbas unknowns.
This is actually what I want. It is very smart to make use of the solve function. Look forward to the eliminate function.
Most helpful comment
Maybe this is what you want:
Ideally we would have an
eliminatefunction rather than needing to solve foraandbas unknowns.