Exercise 1: Floating-Point and Symbolic Precision
- Install and import SymPy
- Use SymPy to demonstrate the limitations of floating-point arithmetic:
- Evaluate ((1 / 49) \times 49) using standard Python floating-point arithmetic.
- Represent the same computation symbolically in SymPy and evaluate.
- Perform (sin(\pi)) using Python’s
math
library and compare it with SymPy’s symbolic result.
- Compare the results and explain why SymPy provides an exact answer.
Exercise 2: Symbolic Manipulations
- Define symbolic variables (x, y, z) and create these expressions:
- (expr1 = \frac{x^2 + 2x + 1}{x+1})
- (expr2 = \sin(x)^2 + \cos(x)^2)
- Perform the following operations:
- Simplify (expr1) and (expr2). Explain the simplifications.
- Substitute (x = \pi/4) in (expr2) and evaluate numerically to verify the trigonometric identity.
- Create a symbolic expression for (expr3 = (x+y)^3 - (x-y)^3). Factorize and expand it.
- Substitute (x = 2), (y = 3), and (z = -1) into the factored form of (expr3) and compute the result.
Exercise 3: Symbolic Substitution and Nested Transformations
- Define (expr = 2x + 3y - z).
- Perform nested substitutions:
- Replace (x) with ((z + 1)).
- Substitute (y) with (2x) in the resulting expression.
- Replace (z) with (x - 2) and simplify the final expression.
- Use SymPy to verify whether the substitutions preserve the equivalence of the original and final expressions.
Bonus: Implement a Python function that takes a symbolic expression and a dictionary of substitutions, applies them recursively, and returns the result.
Exercise 4: Exploring Symbolic Trees
- Define the expression (expr = x^3 + 2x^2 + x + 1).
- Use
sp.srepr(expr)
to examine its internal representation. - Visualize the structure as a tree using
sp.print_tree(expr, assumptions=False)
. - Define a function that:
- Accepts a symbolic expression.
- Computes the depth of the tree.
- Counts the number of unique symbols and operations in the tree.
- More about expression trees here.
Bonus: Test your function on (expr = (x+y)^5 - (x-y)^5) and compare the results with smaller expressions.
Exercise 5: Numerical Functions and Performance
- Define the symbolic expression (f(x) = x^4 - 4x^2 + 3).
- Convert (f(x)) into a numerical function using
sp.lambdify
:- Use Python’s native libraries.
- Use NumPy and evaluate (f(x)) for (x = [-2, -1, 0, 1, 2]).
- Plot (f(x)) using NumPy and Matplotlib.