我最後寫的代碼使用sympy做到這一點的蟒蛇。我想我將把matlab代碼移植到python中,因爲它對我來說是一種更受歡迎的語言。我並沒有聲稱這很快,但它符合我的目的。
# Factors a sum of products function that is first order with respect to all symbolic variables
# into a reduced form using products of sums whenever possible.
# @params orig_exp A symbolic expression to be simplified
# @params depth Used to control indenting for printing
# @params verbose Whether to print or not
def factored(orig_exp, depth = 0, verbose = False):
# Prevents sympy from doing any additional factoring
exp = expand(orig_exp)
if verbose: tabs = '\t'*depth
terms = []
# Break up the added terms
while(exp != 0):
my_atoms = symvar(exp)
if verbose:
print tabs,"The expression is",exp
print tabs,my_atoms, len(my_atoms)
# There is nothing to sort out, only one term left
if len(my_atoms) <= 1:
terms.append((exp, 1))
break
(c,v) = collect_terms(exp, my_atoms[0])
# Makes sure it doesn't factor anything extra out
exp = expand(c[1])
if verbose:
print tabs, "Collecting", my_atoms[0], "terms."
print tabs,'Seperated terms with ',v[0], ', (',c[0],')'
# Factor the leftovers and recombine
c[0] = factored(c[0], depth + 1)
terms.append((v[0], c[0]))
# Combines trivial terms whenever possible
i=0
def termParser(thing): return str(thing[1])
terms = sorted(terms, key = termParser)
while i<len(terms)-1:
if equals(terms[i][1], terms[i+1][1]):
terms[i] = (terms[i][0]+terms[i+1][0], terms[i][1])
del terms[i+1]
else:
i += 1
recombine = sum([terms[i][0]*terms[i][1] for i in range(len(terms))])
return simplify(recombine, ratio = 1)
您使用的是什麼'版本'的Matlab?在R2014b中,'因素(A * B * C)'返回'[A,B,C]'。另一個例子也很好。還是試圖爲作業編寫自己的版本? – horchler 2014-12-02 02:41:58
我在2013b。這不是一項任務,而是一項研究項目。我實際上找到了一個可以完成「孩子」這個工作的功能。我仍在測試它以確保它沒有任何角落案例(我不希望它通過總和,只有產品分割) – Chet 2014-12-02 03:18:04
我無法測試版本之間是否存在差異,但我不會如果有的話會感到驚訝。也許你也可以嘗試使用'sym/factor'的第二個參數。你也可能會發現'symvar'有幫助。如果您找到解決方案,請隨時回答您自己的問題 - 只需指定您使用的是哪個Matlab版本。 – horchler 2014-12-02 03:36:22