gpt4 book ai didi

python - 使用 sympy 将相似的术语放在一起

转载 作者:太空宇宙 更新时间:2023-11-03 18:05:46 25 4
gpt4 key购买 nike

以下代码将类似的术语放在一起。然而,对于大量术语,将所有相似术语相加可能会变得更加困难。关于如何在不使用我目前采用的繁琐方法的情况下实现这一目标的任何建议。

import sympy as sp
from sympy import *
import numpy as np
from numpy.linalg import *
x,y,a,b,c,d=sp.symbols('x,y,a,b,c,d')
A=a*x + b*y
B=c*x+d*y
A1=A.coeff(x)
B1=B.coeff(x) #segregating the coefficients
A2=A.coeff(y)
B2=B.coeff(y)
A_new=(A1+B1)*x + (A2+B2)*y
print A_new

输出为

x*(a + c) + y*(b + d)

最佳答案

import sympy as sp

x,y,a,b,c,d=sp.symbols('x,y,a,b,c,d')
A = a*x + b*y
B = c*x+d*y
sum_expr = A+B
sum_expr.collect((x,y)) # output: x*(a + c) + y*(b + d)

写在 the tutorial也是。

关于python - 使用 sympy 将相似的术语放在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26929405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com