```python
from sympy import *
# from sympy.abc import *
from IPython.display import display
init_printing()
```

# SymPy

## Symbolic Computation
Free, Open Source, Python
- solve equations - simplify expressions
- compute derivatives, integrals, limits
- work with matrices, - plotting & printing
- code gen - physics - statitics - combinatorics
- number theory - geometry - logic

----

## Modules
[SymPy Core](http://docs.sympy.org/latest/modules/core.html) - [Combinatorics](http://docs.sympy.org/latest/modules/combinatorics/index.html) - [Number Theory](http://docs.sympy.org/latest/modules/ntheory.html) - [Basic Cryptography](http://docs.sympy.org/latest/modules/crypto.html) - [Concrete Maths](http://docs.sympy.org/latest/modules/concrete.html) - [Numerical Evaluation](http://docs.sympy.org/latest/modules/evalf.html) - [Code Gen](http://docs.sympy.org/latest/modules/codegen.html) - [Numeric Computation](http://docs.sympy.org/latest/modules/numeric-computation.html) - [Functions](http://docs.sympy.org/latest/modules/functions/index.html) - [Geometry](http://docs.sympy.org/latest/modules/geometry/index.html) - [Holonomic Functions](http://docs.sympy.org/latest/modules/holonomic/index.html) - [Symbolic Integrals](http://docs.sympy.org/latest/modules/integrals/integrals.html) - [Numeric Integrals](http://docs.sympy.org/latest/modules/integrals/integrals.html#numeric-integrals) - [Lie Algebra](http://docs.sympy.org/latest/modules/liealgebras/index.html) - [Logic](http://docs.sympy.org/latest/modules/logic.html) - [Matricies](http://docs.sympy.org/latest/modules/matrices/index.html) - [Polynomials](http://docs.sympy.org/latest/modules/polys/index.html) - [Printing](http://docs.sympy.org/latest/modules/printing.html) - [Plotting](http://docs.sympy.org/latest/modules/plotting.html) - [Pyglet Plotting](http://docs.sympy.org/latest/modules/plotting.html#module-sympy.plotting.pygletplot) - [Assumptions](http://docs.sympy.org/latest/modules/assumptions/index.html) - [Term Rewriting](http://docs.sympy.org/latest/modules/rewriting.html) - [Series Module](http://docs.sympy.org/latest/modules/series/index.html) - [Sets](http://docs.sympy.org/latest/modules/sets.html) - [Symplify](http://docs.sympy.org/latest/modules/simplify/simplify.html) - [Hypergeometrtic](http://docs.sympy.org/latest/modules/simplify/hyperexpand.html) - [Stats](http://docs.sympy.org/latest/modules/stats.html) - [ODE](http://docs.sympy.org/latest/modules/solvers/ode.html) - [PDE](http://docs.sympy.org/latest/modules/solvers/pde.html) - [Solvers](http://docs.sympy.org/latest/modules/solvers/solvers.html) - [Diophantine](http://docs.sympy.org/latest/modules/solvers/diophantine.html) - [Inequality Solvers](http://docs.sympy.org/latest/modules/solvers/inequalities.html) - [Solveset](http://docs.sympy.org/latest/modules/solvers/solveset.html) - [Tensor](http://docs.sympy.org/latest/modules/tensor/index.html) - [Utilities](http://docs.sympy.org/latest/modules/utilities/index.html) - [Parsing Input](http://docs.sympy.org/latest/modules/parsing.html) - [Calculus](http://docs.sympy.org/latest/modules/calculus/index.html) - [Physics](http://docs.sympy.org/latest/modules/physics/index.html) - [Categrory Theory](http://docs.sympy.org/latest/modules/categories.html) - [Differential Geometry](http://docs.sympy.org/latest/modules/diffgeom.html) - [Vector](http://docs.sympy.org/latest/modules/vector/index.html)

----
## Simple Expressions


```python
# declare variable first
x, y = symbols('x y')

# Declare expression
expr = x + 3*y

# Print expressions
print("expr     =", expr)
print("expr + 1 =", expr + 1)
print("expr - x =", expr - x) # auto-simplify
print("x * expr =", x * expr)
```

    expr     = x + 3*y
    expr + 1 = x + 3*y + 1
    expr - x = 3*y
    x * expr = x*(x + 3*y)



----
## Substitution


```python
x = symbols('x')

expr = x + 1
print(expr)
display(expr)
```


```python
# Evaluate expression at a point
print("expr(2)=", expr.subs(x, 2))
```

    expr(2)= 3



```python
# Replace sub expression with another sub expression
# 1. For expressions with symmetry
x, y = symbols('x y')
expr2 = x ** y
expr2 = expr2.subs(y, x**y)
expr2 = expr2.subs(y, x**x)
display(expr2)
```


```python
# 2. Controlled simplifcation
expr3 = sin(2*x) + cos(2*x)
print("expr3")
display(expr3)
print(" ")

print("expand_trig(expr3)")
display(expand_trig(expr3))
print(" ")

print("use this to only expand sin(2*x) if desired")
print("expr3.subs(sin(2*x), 2*sin(x)*cos(x))")
display(expr3.subs(sin(2*x), 2*sin(x)*cos(x)))
```


```python
# multi-substitute
expr4 = x**3 + 4*x*y - z
args = [(x,2), (y,4), (z,0)]
expr5 = expr4.subs(args)
display(expr4)
print("args = ", args)
display(expr5)
```


```python
expr6 = x**4 - 4*x**3 + 4 * x ** 2 - 2 * x + 3
args = [(x**i, y**i) for i in range(5) if i%2 == 0]
display(expr6)
print(args)
display(expr6.subs(args))
```

----
## Equality & Equivalence


```python
# do not use == between symbols and variables, will return false

x = symbols('x')
x+1==4
```




    False




```python
# Create a symbolic equality expression
expr2 = Eq(x+1, 4)
print(expr2)
display(expr2)

print("if x=3, then", expr2.subs(x,3))
```


```python
# two equivalent formulas
expr3 = (x + 1)**2 # we use pythons ** exponentiation (instead of ^)
expr4 = x**2 + 2*x + 1
eq34 = Eq(expr3, expr4)

print("expr3")
display(expr3)

print("                        ≡   expr4")
display(expr4)
print("")

print("(expr3 == expr4)        => ", expr3 == expr4)
print("(these are equivalent, but not the same symbolically)")
print("")

print("Equal by negating, simplifying and comparing to 0")
print("expr3 - expr4           => ", expr3 - expr4)
print("simplify(expr3-expr4)==0=> ", simplify(expr3 - expr4)==0 )
print("")

print("Equals (test by evaluating 2 random points)")
print("expr3.equals(expr4)     => ", expr3.equals(expr4))

```

----
## SymPy Types & Casting


```python
print( "1                     =", type(1) )
print( "1.0                   =", type(1.0) )
print( "Integer(1)            =", type(Integer(1)) )
print( "Integer(1)/Integer(3) =", type(Integer(1)/Integer(3)) )
print( "Rational(0.5)         =", type(Rational(0.5)) )
print( "Rational(1/3)         =", type(Rational(1,3)) )
```

    1                     = <class 'int'>
    1.0                   = <class 'float'>
    Integer(1)            = <class 'sympy.core.numbers.One'>
    Integer(1)/Integer(3) = <class 'sympy.core.numbers.Rational'>
    Rational(0.5)         = <class 'sympy.core.numbers.Half'>
    Rational(1/3)         = <class 'sympy.core.numbers.Rational'>



```python
# string to SymPy
sympify("x**2 + 3*x - 1/2")
```

----

## Evaluating Expressions


```python
# evaluate as float using .evalf(), and N
display( sqrt(8) )
display( sqrt(8).evalf() )
display( sympy.N(sqrt(8)) )
```


```python
# evaluate as float to nearest n decimals
display(sympy.pi)
display(sympy.pi.evalf(100))
```

----

## SymPy Types

#### Number Class
[Number](http://docs.sympy.org/latest/modules/core.html#number) - [Float](http://docs.sympy.org/latest/modules/core.html#float) - [Rational](http://docs.sympy.org/latest/modules/core.html#rational) - [Integer](http://docs.sympy.org/latest/modules/core.html#integer) - [RealNumber](http://docs.sympy.org/latest/modules/core.html#realnumber)

#### Numbers
[Zero](http://docs.sympy.org/latest/modules/core.html#zero) - [One](http://docs.sympy.org/latest/modules/core.html#one) - [Negative One](http://docs.sympy.org/latest/modules/core.html#negativeone) - [Half](http://docs.sympy.org/latest/modules/core.html#half) - [NaN](http://docs.sympy.org/latest/modules/core.html#nan) - [Infinity](http://docs.sympy.org/latest/modules/core.html#infinity) - [Negative Infinity](http://docs.sympy.org/latest/modules/core.html#negativeinfinity) - [Complex Infinity](http://docs.sympy.org/latest/modules/core.html#complexinfinity) 

#### Constants
[E (Transcedental Constant)](http://docs.sympy.org/latest/modules/core.html#exp1) - [I (Imaginary Unit)](http://docs.sympy.org/latest/modules/core.html#imaginaryunit) - [Pi](http://docs.sympy.org/latest/modules/core.html#pi) - [EulerGamma (Euler-Mascheroni constant)](http://docs.sympy.org/latest/modules/core.html#eulergamma) - [Catalan (Catalan's Constant)](http://docs.sympy.org/latest/modules/core.html#catalan) - [Golden Ratio](http://docs.sympy.org/latest/modules/core.html#goldenratio)


### Rational Numbers


```python
# Rational Numbers
expr_rational = Rational(1)/3
print("expr_rational")
display( type(expr_rational) )
display( expr_rational )

eval_rational = expr_rational.evalf()
print("eval_rational")
display( type(eval_rational) )
display( eval_rational )

neval_rational = N(expr_rational)
print("neval_rational")
display( type(neval_rational) )
display( neval_rational )
```

### Complex Numbers


```python
# Complex Numbers supported.
expr_cplx = 2.0 + 2*sympy.I

print("expr_cplx")
display( type(expr_cplx) )
display( expr_cplx )

print("expr_cplx.evalf()")
display( type(expr_cplx.evalf()) )
display( expr_cplx.evalf() )

print("float() - errors")
print(" ")
# this errors complex cannot be converted to float
#display( float(sym_cplx) )

print("complex() - evaluated to complex number")
display( complex(expr_cplx) )
display( type(complex(expr_cplx)) )
```


```python
# Partial Evaluation if cannot be evaluated as float
display( (sympy.pi*x**2 + x/3).evalf(2) )
```


```python
# use substitution in evalf
expr = cos(2*x)
expr.evalf(subs={x:2.4})
```


```python
# sometimes there are round-offs smaller than the desired precision
one = cos(1)**2 + sin(1)**2
display( (one-1).evalf() )
# chop=True can remove these errors
display( (one-1).evalf(chop=True) )
```


```python
import sys
'gmpy2' in sys.modules.keys()
```




    True




```python

```

e7bce31317466b02f49f03142c3434b88f7fc4e2
ipynb
Jupyter Notebook
notebooks/python-data-science/sympy/sympy.ipynb
sparkboom/my_jupyter_notes
9255e4236b27f0419cdd2c8a2159738d8fc383be
MIT
notebooks/python-data-science/sympy/sympy.ipynb
sparkboom/my_jupyter_notes
9255e4236b27f0419cdd2c8a2159738d8fc383be
MIT
notebooks/python-data-science/sympy/sympy.ipynb
sparkboom/my_jupyter_notes
9255e4236b27f0419cdd2c8a2159738d8fc383be
MIT
Qwen/Qwen-72B
1. YES
2. YES