求和检查计算

时间:2018-06-22 21:56:58

标签: sympy

如何使用Sympy逐步检查计算结果,例如以下两个公式是否相等?

from sympy import IndexedBase, Sum, symbols
i, n = symbols('i n', integer=True)
a = IndexedBase('a')

Sum(a[i], (i, 0, n - 1)) + a[n]
Sum(a[i], (i, 0, n))

1 个答案:

答案 0 :(得分:0)

简单函数用于检查两个表达式是否相等。

from sympy import IndexedBase, Sum, symbols, simplify

i, n = symbols('i n', integer=True)
a = IndexedBase('a')
#to check calculations
n=5
x=Sum(a[i], (i, 0, n - 1)).doit() + a[n].doit()
y=Sum(a[i], (i, 0, n)).doit()
print x,y
#To check functions are equal
if simplify(x-y) == 0:
    print "The two functions are equal"