简体   繁体   中英

How can I define a symbolic function in python?

I am writing a very simple macro for my thesis.

I want to define a symbolic function with 4 input parameters: two of them correspond to numerical values but the other two are symbolic variables that will be used for integrating the function.

Here is the code of the function:

def VelocityDistribution_notNorm(v_DM,costheta,v_0,v_e):
    return exp(-(v_DM**2 + v_e**2 + 2*v_DM*v_e*costheta)/(v_0**2));

v_0 and v_e correspond to numerical values and V_DM and costheta are the two symbolic variables. In a different function I called the previous function in the following way:

v_0 = 220 #km/s
v_e = 232 #km/s
v_DM = Symbol("v_DM")
cosTheta = Symbol("cosTheta")
integrand_0 = v_DM * VelocityDistribution_notNorm(v_DM,v_e,v_0,cosTheta)

Also I imported the following modules:

from math import *
from sympy import *
from sympy.functions.elementary.exponential import *
from scipy import *
from scipy.constants import *

but I get this error when I try to run the macro:

  File "prova.py", line 38, in VelocityDistribution_notNorm
    return exp(-(v_DM**2 + v_e**2 + 2*v_DM*v_e*costheta)/(v_0**2));
AttributeError: 'Add' object has no attribute 'exp'

What I am doing wrong?

the function exp is in the math package. Import it before use:

from math import exp

I think you're mixing symbolic and explicit functions, here. You can solve this by not importing anything from math. This is why it is generally advised against doing from xyz import *

from sympy import *
import scipy

def VelocityDistribution_notNorm(v_DM,costheta,v_0,v_e):
    return exp(-(v_DM**2 + v_e**2 + 2*v_DM*v_e*costheta)/(v_0**2));

v_0 = 220 #km/s
v_e = 232 #km/s
v_DM = Symbol("v_DM")
cosTheta = Symbol("cosTheta")
integrand_0 = VelocityDistribution_notNorm(v_DM,v_e,v_0,cosTheta)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM