user3059024 February 2016
### Using Python's sympy module to express a complicated function

How can I symbolically express the following equation using python's sympy module, such that I could later find the second derivative and therefore compute the Hessian matrix?

The Function

What I've tried:

```
import sympy
Nc,Ns,Tc,Ysc,theta,theta_star,t,dt,sigma_s,measured,simulated=sympy.symbols(' Nc Ns Tc Ysc theta theta_star t dt sigma_s measured simulated ')
chi=(1/2*Nc*Ns) * sympy.mpmath.nsum( 1 / Tc * sympy.integrate( ((simulated - measured) / sigma_s ) **2) , (t,0,Tc))
```

The Error:

```
File "C:\Anaconda1\lib\site-packages\sympy\concrete\expr_with_limits.py", line 358, in __new__
"specify dummy variables for %s" % function)
ValueError: specify dummy variables for (-measured + simulated)**2/sigma_s**2
```

jgfооt February 2016

The problem is that you are telling it to integrate with the integration variable of t, but the function `((simulated - measured) / sigma_s ) **2`

doesn't have t as a variable.

asmeurer February 2016

Don't use `sympy.mpmath.nsum`

. mpmath functions are for numerical calculations only. Do represent a sum symbolically, use `sympy.Sum`

. It works like this

```
In [3]: Sum(f(x), (x, 0, n))
Out[3]:
n
___
╲
╲ f(x)
╱
╱
‾‾‾
x = 0
```

Secondly, SymPy has to be told explicitly when one variable depends on another. I'm unclear what `s`

and `c`

are in your equation. If they are variables, then you should create symbols `s`

and `c`

. Importantly, `t`

needs to be a variable, and things that depend on `t`

need to be functions like

```
thetastar, t = symbols('thetastar t')
y_sc = Function('y')
```

and then use

```
y_sc(thetastar, t)
```

(if `s`

and `c`

are supposed to be variables as well, then you should use `y = Function('y')`

and `y(s, c, thetastar, t)`

).

Asked in February 2016

Viewed 3,103 times

Voted 5

Answered 2 times

Viewed 3,103 times

Voted 5

Answered 2 times