python: changing symbol variable and assign numerical value

最后都变了- 提交于 2021-01-24 07:25:46

问题


In order to calculate derivatives and other expressions I used the sympy package and said that T = sy.Symbol('T') now that I have calculated the right expression:

E= -T**2*F_deriv_T(T,rho)

where

def F_deriv_rho(T,rho):
    ret = 0
    for n in range(5):
        for m in range(4):
            inner= c[n,m]*g_rho_deriv_rho_np*g_T_np
        ret += inner
    return ret

that looks like this:

F_deriv_rho: [0.0 7.76971e-5*T 0.0001553942*T**2*rho T*(-5.14488e-5*log(rho) - 5.14488e-5)*log(T) + T*(1.22574e-5*log(rho)+1.22574e-5)*log(T) + T*(1.89488e-5*log(rho) + 1.89488e-5)*log(T) + T(2.29441e-5*log(rho) + 2.29441e-5)*log(T) + T*(7.49956e-5*log(rho) + 7.49956e-5)*log(T) T**2*(-0.0001028976*rho*log(rho) - 5.14488e-5*rho)*log(T) + T**2*(2.45148e-5*rho*log(rho) + 1.22574e-5*rho)*log(T) + T**2*(3.78976e-5*rho*log(rho) + 1.89488e-5*rho)*log(T) + T**2*(4.58882e-5*rho*log(rho) + 2.29441e-5*rho)*log(T) + T**2*(0.0001499912*rho*log(rho) + 7.49956e 5*rho)*log(T)]

with python I would like to change T (and rho) as a symbol to a value. How could I do that?

So, I would like to create 10 numbers like T_def = np.arange(2000, 10000, 800)and exchange all my sy.symbol(T) by iterating through the 10 values I created in the array.

Thanks for your help


回答1:


I have found the solution according to this post:

How to substitute multiple symbols in an expression in sympy?

by usings "subs":

>>> from sympy import Symbol
>>> x, y = Symbol('x y')
>>> f = x + y
>>> f.subs({x:10, y: 20})
>>> f
    30

There's more for this kinda thing here: http://docs.sympy.org/latest/tutorial/basic_operations.html

EDIT: A faster way would be by using "lamdify" as suggested by @Bjoern Dahlgren



来源:https://stackoverflow.com/questions/40609184/python-changing-symbol-variable-and-assign-numerical-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!