Reputation: 23
I have tried extracting coefficients of a trignometric expression using multiple methods (symp.coeff
, as_coefficient
). The code is as follows:
import sympy as sy
x1 = sy.symbols('x1')
A, B = sy.symbols('A,B')
L = sy.symbols('L', positive=True)
f = (A * sy.sin(sy.pi * x1 / (2 * L)) + B * sy.cos(sy.pi * x1 / (2 * L))) / L ** 2
c1 = f.coeff(sy.cos(sy.pi * x1 / (2 * L)))
# or
c1 = f.as_coefficient(sy.cos(sy.pi * x1 / (2 * L)))
display(c1)
The output that is expected is B/L**2
. But in the first case, I get the output to be 0 while in the second case I get to be "None".
Can someone please guide me in how to extract the coefficient?
Upvotes: 0
Views: 37
Reputation: 231385
I get what you want if I expand
the expression, so it's a simple sum, not a product:
In [3]: f
Out[3]:
⎛π⋅x₁⎞ ⎛π⋅x₁⎞
A⋅sin⎜────⎟ + B⋅cos⎜────⎟
⎝2⋅L ⎠ ⎝2⋅L ⎠
─────────────────────────
2
L
In [6]: f.expand()
Out[6]:
⎛π⋅x₁⎞ ⎛π⋅x₁⎞
A⋅sin⎜────⎟ B⋅cos⎜────⎟
⎝2⋅L ⎠ ⎝2⋅L ⎠
─────────── + ───────────
2 2
L L
In [7]: f1 = f.expand()
In [8]: f1.coeff(cos(pi*x1/(2*L)))
Out[8]:
B
──
2
L
compare the types:
In [9]: type(f)
Out[9]: sympy.core.mul.Mul
In [10]: type(f1)
Out[10]: sympy.core.add.Add
Upvotes: 1