【发布时间】:2018-10-13 18:30:14
【问题描述】:
假设我有一个使用 sympy 的总结
from sympy import *
import numpy as np
m = 10
n = IndexedBase('n')
i = symbols("i",cls=Idx)
sum_ = summation(n[i],[i,1,m])
sum_
>>> n[10] + n[1] + n[2] + n[3] + n[4] + n[5] + n[6] + n[7] + n[8] + n[9]
和一个 numpy 值数组
a = np.random.random((m,))
我想使用a 的每个对应值来评估sum_ - 例如n[1] 将是a[0],n[2] 将是a[1] 等等。如何将a 的值传递给n?
我曾尝试使用doit() 方法,但我不确定它是如何工作的,并且不断出错。
此外,假设我有一个复杂的函数,其中包含总和,我想对其求导,然后评估系数和变量的特定值,如下所示
theta0 = Symbol('theta0')
theta1 = Symbol('theta1')
theta2 = Symbol('theta2')
sigma = Symbol('sigma')
sigma0 = Symbol('sigma0')
sigma1 = Symbol('sigma1')
sigma2 = Symbol('sigma2')
x = IndexedBase('x')
t = IndexedBase('t')
i = symbols("i", cls=Idx)
nges = -(1/(2*sigma**2))*summation( (x[i] - theta0 - theta1*t[i] -
theta2*t[i]**2)**2, [i, 1, 2])
func = (-1/2)*((theta0/sigma0)**2 + (theta1/sigma1)**2 +
(theta2/sigma2)**2) + nges
diff(func, theta0, 1)
>>> -1.0*theta0/sigma0**2 - (4*theta0 + 2*theta1*t[1] + 2*theta1*t[2] + 2*theta2*t[1]**2 + 2*theta2*t[2]**2 - 2*x[1] - 2*x[2])/(2*sigma**2)
如何传递theta 的标量值和x 和t 的向量(numpy 数组)? (我尝试使用.limit(),但这变得很麻烦,因为我必须在一个表达式上多次调用它)
【问题讨论】: