
# sympyTests.py
# https://www.sympy.org/
'''
  A version of this code is executed by JEP inside
  JepSympy.java

  The examples include:
    * simplify, factor, substitute, series 
    * sums, products
    * derivative, integration
    * printing using ASCII art and mathML
    * limits
    * solving quadratic equations
    * matricies
'''

from sympy import *
 
x = Symbol('x')
y = Symbol('y')
n = Symbol('n')

z = (x + y) + (x - y)
print("z = " + str(z))

 
expr = 2*x + 3*x - sin(x) - 3*x + 42
print(expr, "or", simplify(expr))
print()

expr = x**2 - 2*x - 8
print(expr, "factored =", factor(expr))
print()

expr = sin(x) + cos(y)
print(expr.subs({x:1, y:2}))
print(expr.subs({x:1, y:2}).n())
print()

exp_xn = x**n/factorial(n)
print(summation( exp_xn.subs({x:5}), [n, 0, oo] ).evalf())
print(exp(5).evalf())  # the true value
print()

print(exp(x).series())
print()

print(Sum(1/(n**2), (n, 1, oo)))
print(Sum(1/(n**2), (n, 1, oo)).doit())
print()

print(Product(n, (n, 1, 7)))
print(Product(n, (n, 1, 7)).doit())
print()

# derivative of sin(x)*e ^ x
ans1 = diff(sin(x)*exp(x), x)
print("derivative of sin(x)*e^x == ", ans1)
print()

expr = x**4 + x**3 + x**2 + x + 1
print("derivatives of", expr)
print(expr.diff(x))
print(expr.diff(x, x))
print(expr.diff(x, x, x))
print()

expr = sin(x * y) * cos(x / 2)
print("derivatives of", expr)
print(expr.diff(x))
print()

# Compute (e ^ x * sin(x)+ e ^ x * cos(x))dx
ans = integrate(exp(x)*sin(x) + exp(x)*cos(x), x)
print("indefinite integration == ", ans)
print()

# definite integral of sin(x ^ 2)dx  between -inf and -inf
ans = integrate(sin(x**2), (x, -oo, oo))
print("definite integration == ", ans)
print()
 
a = Symbol('a')
b = Symbol('b')
ans = integrate(sin(x), (x, a, b))
print("definite integration == ", ans)
print()

print(pretty(Integral(sqrt(1/x), x), use_unicode=False))
print()

print(print_mathml(Integral(sqrt(1/x), x), 
                   printer='presentation'))
print()


# limit of sin(x) / x as x tends to 0
ans = limit(sin(x)/x, x, 0)
print("limit == ", ans)
print()

# Solve quadratic equation x ^ 2 - 2 = 0
ans = solve(x**2 - 2, x)
print("roots == ", ans)
print()

a, b, c = symbols('a b c')
print(solve( a*x**2 + b*x + c, x))


a, b, c, d = symbols("a, b, c, d")
M = Matrix([[a, b], [c, d]])
print(M)
print("M*M =", M*M)
print()

A = Matrix([[ 2,-3,-8, 7],
            [-2,-1, 2,-7],
            [ 1, 0,-3, 6]] )
print(A[0,1]) # row 0, col 1 of A
print(A[0:2,0:3]) # top-left 2x3 submatrix of A
print()

print(eye(2)) # 2x2 identity matrix
print(zeros(2, 3))
print()



