This is actually a quite simple task to do manually, given the two equation, but nevertheless I wanted to know if its possible to equate coefficients in python (maybe using numpy or sympy/scipy?). So the equations I have look something like this:
y = 1.0066*x**2-1.8908*x-0.888
U = 0.5kB*(r-r0)**2
Now ideally the second equation should be first multiplied out to take shape like the one above and then kB should be calculated via the three coefficients a (=1.0066), b(=1.8908) and c (0.888) with r0 being a constant aswell (basically giving me 3 values for kB) So the only variables are x and r ,but I am not really interested in them
Is it possible to perform such a task? Bare in mind that I am just a beginner
Thank you
You could use SymPy
to represent the right-hand sides as expressions with respect to symbolic variables x
, r
, r0
and kB
:
x, r, r0, kB = sym.symbols('x,r,r0,kB')
y = 1.0066*x**2-1.8908*x-0.888
U = 0.5*kB*(r-r0)**2
Now we can convert y
and U
into polynomials with respect to x
and r
:
In [39]: sym.poly(y, x)
Out[39]: Poly(1.0066*x**2 - 1.8908*x - 0.888, x, domain='RR')
In [40]: sym.poly(U, r)
Out[40]: Poly(0.5*kB*r**2 - 1.0*kB*r0*r + 0.5*kB*r0**2, r, domain='RR[r0,kB]')
sym.Poly
s have a all_coeffs
method which returns a list of the coefficients:
In [41]: sym.poly(y, x).all_coeffs()
Out[41]: [1.00660000000000, -1.89080000000000, -0.888000000000000]
In [42]: sym.poly(U, r).all_coeffs()
Out[42]: [0.5*kB, -1.0*kB*r0, 0.5*kB*r0**2]
We can use zip
to pair the coefficients from the two lists:
In [43]: list(zip(sym.poly(y, x).all_coeffs(), sym.poly(U, r).all_coeffs()))
Out[43]:
[(1.00660000000000, 0.5*kB),
(-1.89080000000000, -1.0*kB*r0),
(-0.888000000000000, 0.5*kB*r0**2)]
and then use sympy.Eq
to equate the expressions, and use sympy.solve
to solve them for kB
. The Python construct I'm using here to generate the list is called a list comprehension :
In [44]: [sym.solve(sym.Eq(a, b), [kB]) for a, b in zip(sym.poly(y, x).all_coeffs(), sym.poly(U, r).all_coeffs())]
Out[44]: [[2.01320000000000], [1.8908/r0], [-1.776/r0**2]]
Putting it all together:
import sympy as sym
x, r, r0, kB = sym.symbols('x,r,r0,kB')
y = 1.0066*x**2-1.8908*x-0.888
U = 0.5*kB*(r-r0)**2
result = [sym.solve(sym.Eq(a, b), [kB]) for a, b in
zip(sym.poly(U, r).all_coeffs(), sym.poly(y, x).all_coeffs())]
print(result)
prints
[[2.01320000000000], [1.8908/r0], [-1.776/r0**2]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.