Lab 2

Exercise 1: Floating-Point and Symbolic Precision

  1. Install and import SymPy
  2. 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.
  3. Compare the results and explain why SymPy provides an exact answer.

Exercise 2: Symbolic Manipulations

  1. 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)
  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.
  3. Create a symbolic expression for (expr3 = (x+y)^3 - (x-y)^3). Factorize and expand it.
  4. 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

  1. Define (expr = 2x + 3y - z).
  2. 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.
  3. 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

  1. Define the expression (expr = x^3 + 2x^2 + x + 1).
  2. Use sp.srepr(expr) to examine its internal representation.
  3. Visualize the structure as a tree using sp.print_tree(expr, assumptions=False).
  4. 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

  1. Define the symbolic expression (f(x) = x^4 - 4x^2 + 3).
  2. 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]).
  3. Plot (f(x)) using NumPy and Matplotlib.