代码之家  ›  专栏  ›  技术社区  ›  PyRsquared

如何使用显式值计算带索引变量的SymPy表达式?

  •  0
  • PyRsquared  · 技术社区  · 8 年前

    假设我用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]
    

    a = np.random.random((m,))
    

    我想评估一下 sum_ a n[1] 会是 a[0] , n[2] 会是 a[1] 等等。如何传递 一 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 的和向量(numpy数组) x 的和 t 是谁(我试过用 .limit()

    1 回复  |  直到 8 年前
        1
  •  1
  •   user6655984 user6655984    8 年前

    最简单的方法是使用 .subs

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

    在某些情况下,您还需要调用 evalf pi 评价的。在这种情况下,建议在 评估 这样地:

    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
    
    推荐文章