Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell sympy that i^2 = -1?

Tags:

python

sympy

I'm currently using sympy to check my algebra on some nasty equations involving second order derivatives and complex numbers.

import sympy
from sympy.abc import a, e, i, h, t, x, m, A

# define a wavefunction
Psi = A * sympy.exp(-a * ((m*x**2 /h)+i*t))

# take the first order time derivative
Psi_dt = sympy.diff(Psi, t)
# take the second order space derivative
Psi_d2x = sympy.diff(Psi, x, 2)

# write an expression for energy potential (rearrange Schrodingers Equation)
V = 1/Psi * (i*h*Psi_dt + (((h**2)/2*m) * Psi_d2x))


# symplify potential function
sympy.simplify(V)

Which yields this nice thing:

a*(-h*i**2 + m**2*(2*a*m*x**2 - h))

It would be really nice if sympy simplified i^2 to -1. So how do I tell it that i represents the square root of -1?

On a related note, it would also be really nice to tell sympy that e is eulers number, so if I call sympy.diff(e**x, x) I get e**x as output.

like image 966
Andrew Micallef Avatar asked May 19 '21 05:05

Andrew Micallef


People also ask

How do you evaluate an expression in SymPy?

To evaluate a numerical expression into a floating point number, use evalf . SymPy can evaluate floating point expressions to arbitrary precision. By default, 15 digits of precision are used, but you can pass any number as the argument to evalf .

How do you substitute values in SymPy?

The subs() function in SymPy replaces all occurrences of first parameter with second. This function is useful if we want to evaluate a certain expression. For example, we want to calculate values of following expression by substituting a with 5.

How do I isolate a variable in SymPy?

To isolate one variable, call the solve function, and pass that variable as the second argument. The brackets surround a list of all solutions—in this case, just one. That solution is that R = P V T n .


1 Answers

You need to use the SymPy built-ins, rather than treating those symbols as free variables. In particular:

from sympy import I, E

I is sqrt(-1); E is Euler's number.

Then use the complexes methods to manipulate the complex numbers as needed.

like image 180
Prune Avatar answered Oct 22 '22 10:10

Prune