【问题标题】:How to evaluate SymPy expressions with indexed variables using explicit values?如何使用显式值评估带有索引变量的 SymPy 表达式?
【发布时间】: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 的标量值和xt 的向量(numpy 数组)? (我尝试使用.limit(),但这变得很麻烦,因为我必须在一个表达式上多次调用它)

【问题讨论】:

    标签: python sympy


    【解决方案1】:

    最简单的方法是使用.subs,传入一个替换字典。

    sum_.subs({n[i+1]: a[i] for i in range(m)})
    

    在某些情况下,您还需要调用 evalf 来评估任何符号常量,例如 pi。在这种情况下,建议在 evalf 中包含这样的替换:

    sum_.evalf(subs={n[i+1]: a[i] for i in range(m)})
    

    对于您的第二个示例也是如此。先准备一个带值的dict比较方便。

    values = {theta0: 0.2, theta1: 0.3, theta2: 1.3, sigma0: 2, sigma: 2.2}
    values.update({t[i]: 3*i for i in range(1, 3)})
    values.update({x[i]: 5*i for i in range(1, 3)})
    diff(func, theta0, 1).subs(values)   # 9.67809917355372
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      相关资源
      最近更新 更多