如何将“积和”转化为“有理表达式”p(x)/q(x

2024-04-24 10:22:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让sympy产生并输出两个多项式的商:p/q

import sympy as sp
sp.init_printing()

a,b,c = sp.symbols("a b c")

N=a*b*100 - (a**2) * (b**2)
D=2*(a-b)

V = N / D
print(V)
#Output: (-a**2*b**2 + 100*a*b)/(2*a - 2*b)

# HERE"s WHERE I GET THE RESULT:
g = V.diff(a)
print(g)
#Output: (-2*a*b**2 + 100*b)/(2*a - 2*b)   
             -2*(-a**2*b**2 + 100*a*b)/(2*a - 2*b)**2
# The problem here is that its the sum of two terms

# So I try simplifying it to get it as p/q
h= g.simplify()
print(h)
# Output: b*(a*(a*b - 100) + 2*(a - b)*(-a*b + 50)) / (2*(a - b)**2)
#
# It works to get the function as "p/q", except now
# it didn't expand the numerator and denominator into 
# into a sum of polynomial terms.  how to undo the factoring
# of numerator and denominator while still maintaining the whole
# function as a rational function of the form p/q? 

我想让它看起来像这样:

(-2*a2*b2-4*a*b3)/(4a+4b2)


Tags: andofthetooutputgetasit
1条回答
网友
1楼 · 发布于 2024-04-24 10:22:04

您可以将关键字numer=True或denom=True与expand一起使用:

>>> q
(x + 1)*(x + 2)/((x - 2)*(x - 1))

>>> q.expand(numer=True)
(x**2 + 3*x + 2)/((x - 2)*(x - 1))

>>> _.expand(denom=True)
(x**2 + 3*x + 2)/(x**2 - 3*x + 2)

如何修复上述问题:

import sympy as sp
sp.init_printing()

a,b,c = sp.symbols("a b c")

N=a*b*100 - (a**2) * (b**2)
D=2*(a-b)

N / D
_.diff(a)
_.simplify()
_.expand(numer=True)
_.expand(denom=True)
V = _

另一种方法是使用cancel()方法,它基本上做相同的事情(尽管名称有点不直观):

import sympy as sp
sp.init_printing()

a,b,c = sp.symbols("a b c")

N=a*b*100 - (a**2) * (b**2)
D=2*(a+b)
V = N / D
V.diff(a).cancel()

相关问题 更多 >