Home > Back-end >  Sympy Substitution on the output of variable
Sympy Substitution on the output of variable

Time:11-18

In my code I have a variable h set to an integration. I would like to perform a coordinate change on the output of that integration. Using a computer algebra software like Maple this is achieved by substituting the coordinate change into the variable h, where the substitution takes place on the output of the integration. I tried the following code:

import sympy as sp

r = sym.Symbol('r')
R = sym.Symbol('R')
theta00 = sp.pi*sp.exp(-(r**2-1)/2)

h = sp.integrate((r**2/2)*sp.diff(theta00, r), (r, -sp.oo, R))
hxy = h.subs(sp.sqrt((x-1)**2   y**2), R)

The output of hxy is the same as the output of h, without the required substitution. I think the substitution is being applied before the integration. Is there a way to work with the output of the integration in the variable h?

CodePudding user response:

You have to make sure that the veariables you are using are sympy symbols. Here I am using the symbols from sympy.abc directly.

Then for the substitution you can create use a dictionary mapping variables in your formulas to the substituted value.

import sympy as sp
from sympy.abc import r, R, x, y
theta00 = sp.pi*sp.exp(-(r**2-1)/2)
h = sp.integrate((r**2/2)*sp.diff(theta00, r), (r, -sp.oo, R))

enter image description here

hxy = h.subs({R: sp.sqrt((x-1)**2   y**2)})

enter image description here

You could also replace by a numeric value

h.subs({R: 3})

enter image description here

  • Related