Project 7: Derivative Explorer (Calculus Visualization)

Build a calculator-plus-visualizer that estimates derivatives numerically, draws tangent lines, and helps you reason about when derivative estimates are trustworthy.

Quick Reference

Attribute Value
Difficulty Level 2 (Intermediate)
Time Estimate 8-12 hours
Main Programming Language Python
Alternative Languages JavaScript, C++
Knowledge Area Differential calculus
Recommended Libraries/Tools Expression parser, plotting library, CLI argument parser
Main Book “Calculus” by James Stewart (Derivative chapters)
Deliverable CLI + plotted outputs showing f(x), f'(x) estimate, and tangent line at chosen points

Learning Objectives

By the end of this project, you should be able to:

  1. Explain derivative as instantaneous rate of change and as slope of tangent.
  2. Implement forward, backward, and central-difference derivative estimates.
  3. Choose a step size h intentionally, instead of guessing.
  4. Detect and communicate where derivative estimates are unstable or misleading.
  5. Validate numerical results against known analytic derivatives.
  6. Build clear visual output that supports mathematical reasoning, not just pretty plots.

All Theory Needed per Concept

Concept 1: Derivative as a Limit of Secant Slopes

What you need:

  • Secant slope over interval [x, x+h]: (f(x+h) - f(x)) / h
  • Derivative definition: f'(x) = lim(h->0) (f(x+h)-f(x))/h
  • Geometric meaning: derivative is tangent slope.

Why it matters here:

  • Every numerical method in this project is a finite, computable version of this limit.
  • Your plots should show secant behavior converging toward tangent behavior.

Failure mode to watch:

  • Assuming derivative exists everywhere. Example: f(x)=|x| at x=0 has no single tangent slope.

Practical check:

  • For f(x)=x^2, derivative at x=3 should approach 6 as h decreases (until floating-point noise appears).

Concept 2: Finite Differences and Accuracy Order

What you need:

  • Forward difference: D_f = (f(x+h)-f(x))/h
  • Backward difference: D_b = (f(x)-f(x-h))/h
  • Central difference: D_c = (f(x+h)-f(x-h))/(2h)

Accuracy intuition:

  • Forward/backward: first-order error, roughly proportional to h.
  • Central: second-order error, roughly proportional to h^2 for smooth functions.

Why it matters here:

  • Central difference is usually better at same h, but still fails near discontinuities or noisy inputs.

Failure mode to watch:

  • Declaring “smaller h is always better.” Below a point, round-off dominates and error grows.

Practical check:

  • Run an h sweep (1e-1 to 1e-8) and plot absolute error vs h on log scale.

Concept 3: Numerical Error (Truncation vs Round-Off)

What you need:

  • Truncation error: from replacing a limit/series with finite approximation.
  • Round-off error: from finite precision arithmetic.
  • Total error has a U-shape as h shrinks: first down, then up.

Why it matters here:

  • Your explorer should teach this tradeoff directly, not hide it.
  • You should expose h as a user parameter and possibly suggest a default range.

Failure mode to watch:

  • Using a global fixed h for all scales of x and all functions.

Practical check:

  • Compare derivative estimate for f(x)=sin(x) at x=1 using multiple h values and record error trend.

Concept 4: Tangent Line Construction and Interpretation

What you need:

  • Tangent line at point x0: y_tan(x) = f(x0) + f'(x0)*(x - x0)
  • Interpret sign of slope (increasing/decreasing) and magnitude (how steep).

Why it matters here:

  • Tangent line overlay is where users visually connect derivative output with original curve behavior.

Failure mode to watch:

  • Plotting too wide of an x-range for tangent line; line appears misleading if local linearity is weak far from x0.

Practical check:

  • Draw tangent only on a local window around x0 and compare with full-window tangent.

Project Specification

Build a command-line tool named “Derivative Explorer” with these requirements:

  • Inputs:
    • Function expression f(x).
    • Evaluation point x0.
    • Derivative method (forward, backward, central).
    • Step size h.
    • Plot interval [xmin, xmax] and sample count.
  • Processing:
    • Parse and safely evaluate f(x) on scalars and arrays.
    • Estimate derivative at x0.
    • Generate tangent line from estimate.
    • Optionally estimate derivative curve over grid.
  • Outputs:
    • Numeric report: f(x0), f'(x0) estimate, method, h.
    • Plot with function, tangent line, and optional derivative curve.
    • Warning messages for unstable points (NaN, huge oscillation across nearby h).

Non-negotiable constraints:

  • No hidden symbolic differentiation.
  • Explicitly print chosen method and h.
  • Show at least one validation run against a known derivative.

Solution Architecture (ASCII)

+-------------------------+
| CLI / Input Parameters  |
| f(x), x0, method, h     |
+-----------+-------------+
            |
            v
+-------------------------+
| Safe Expression Engine  |
| parse + evaluate f(x)   |
+-----------+-------------+
            |
            v
+-------------------------+
| Sampling Module         |
| x-grid, f(x)-values     |
+-----------+-------------+
            |
            +----------------------------+
            |                            |
            v                            v
+-------------------------+   +--------------------------+
| Derivative Estimator    |   | Tangent Builder          |
| forward/back/central    |   | y=f(x0)+m(x-x0)          |
+-----------+-------------+   +------------+-------------+
            |                              |
            +---------------+--------------+
                            v
                  +------------------------+
                  | Visualization + Report |
                  | curves, labels, stats  |
                  +------------------------+

Implementation Guide

Phase 1: Input and Function Evaluation

  1. Define CLI contract and required arguments.
  2. Restrict allowed math functions and constants (sin, cos, exp, pi, etc.).
  3. Add robust input validation for expression, x0, and h > 0.

Pseudocode:

read args
validate method in {forward, backward, central}
validate h > 0
compile expression with safe namespace
f(x) -> numeric

Phase 2: Derivative Engine

  1. Implement all three finite-difference formulas.
  2. Keep method selection explicit and testable.
  3. Return both estimate and diagnostic metadata (method, h, nearby evaluations).

Pseudocode:

if method == forward:
    m = (f(x0+h)-f(x0))/h
elif method == backward:
    m = (f(x0)-f(x0-h))/h
else:
    m = (f(x0+h)-f(x0-h))/(2*h)

Phase 3: Tangent and Plotting

  1. Compute y0 = f(x0) and tangent equation using slope m.
  2. Sample function curve across [xmin, xmax].
  3. Plot function, marked point (x0, y0), and local tangent segment.

Phase 4: Stability Diagnostics

  1. Add optional h sweep mode.
  2. Measure absolute difference to known derivative when available.
  3. Emit warning when estimates vary drastically for neighboring h values.

Phase 5: Final Reporting

  1. Standardize textual output format.
  2. Save plot artifact with deterministic filename pattern.
  3. Include metadata banner in plot title (method, h, x0).

Testing Strategy

Use deterministic test cases with clear tolerances.

Numeric Correctness Tests

  1. Polynomial baseline:
    • f(x)=x^2, x0=3
    • Expected derivative: 6
    • Tolerance target with central difference and h=1e-4: |estimate-6| < 1e-3
  2. Trigonometric baseline:
    • f(x)=sin(x), x0=1
    • Expected derivative: cos(1)
  3. Exponential baseline:
    • f(x)=exp(x), x0=0
    • Expected derivative: 1

Stability Tests

  1. h sweep for smooth function to show U-shaped error trend.
  2. Non-differentiable point test:
    • f(x)=abs(x), x0=0
    • Tool should warn that derivative is method-dependent / unstable.

Output and UX Tests

  1. Missing argument handling returns clear error message.
  2. Invalid method or non-positive h rejected.
  3. Plot contains labeled legend entries for all drawn elements.

Common Pitfalls

  1. Tiny h gives worse answers:
    • Cause: floating-point cancellation.
    • Fix: test multiple h; prefer central difference in a moderate h range.
  2. Exploding values near discontinuity:
    • Cause: function undefined near x0.
    • Fix: pre-check domain and report invalid neighborhoods.
  3. Tangent line looks “wrong”:
    • Cause: displayed over too wide interval.
    • Fix: restrict tangent drawing to local window around x0.
  4. False confidence from one test:
    • Cause: only validating on polynomials.
    • Fix: include trig and exponential test suite.

Extensions

  1. Add second-derivative estimator to infer concavity.
  2. Implement secant-line animation converging to tangent line.
  3. Add automatic step-size suggestion based on local scale.
  4. Support piecewise functions with breakpoint annotations.
  5. Add batch mode to compute derivatives at multiple points and export CSV.

Real-World Connections

  1. Physics: velocity and acceleration from position-time data.
  2. Finance: marginal change of cost/revenue with respect to quantity.
  3. Biology: growth rate estimation from population measurements.
  4. Engineering: sensitivity analysis (dy/dx) in design parameters.

Resources

  • James Stewart, Calculus (derivative chapters).
  • Chapra & Canale, Numerical Methods for Engineers (finite difference error analysis).
  • Gilbert Strang, Calculus lectures (derivative intuition and visualization).
  • Python plotting and numerical docs for your chosen libraries.

Self-Assessment

Answer these without running the tool:

  1. Why does central difference usually beat forward difference for smooth functions?
  2. What two errors compete when choosing h?
  3. Why can f(x)=|x| at x=0 produce conflicting derivative estimates?
  4. How would you convince a classmate that derivative is local, not global?
  5. If your estimate changes from 4.8 to 12.1 when h changes slightly, what should you inspect first?

Submission Criteria

A submission is complete only if all items below are satisfied:

  • Project includes a clear CLI contract (inputs, options, output format).
  • Supports at least forward and central differences.
  • Produces a plot with function + tangent at selected point.
  • Includes at least 3 correctness tests against known derivatives.
  • Includes at least 1 instability demonstration (h sweep or non-differentiable case).
  • Documents limitations and when derivative estimates should not be trusted.
  • Provides sample run logs and generated plot artifacts.