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:
- Explain derivative as instantaneous rate of change and as slope of tangent.
- Implement forward, backward, and central-difference derivative estimates.
- Choose a step size
hintentionally, instead of guessing. - Detect and communicate where derivative estimates are unstable or misleading.
- Validate numerical results against known analytic derivatives.
- 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|atx=0has no single tangent slope.
Practical check:
- For
f(x)=x^2, derivative atx=3should approach6ashdecreases (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^2for 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
his always better.” Below a point, round-off dominates and error grows.
Practical check:
- Run an
hsweep (1e-1to1e-8) and plot absolute error vshon 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
hshrinks: first down, then up.
Why it matters here:
- Your explorer should teach this tradeoff directly, not hide it.
- You should expose
has a user parameter and possibly suggest a default range.
Failure mode to watch:
- Using a global fixed
hfor all scales ofxand all functions.
Practical check:
- Compare derivative estimate for
f(x)=sin(x)atx=1using multiplehvalues 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
x0and 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.
- Function expression
- 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.
- Parse and safely evaluate
- 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 nearbyh).
- Numeric report:
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
- Define CLI contract and required arguments.
- Restrict allowed math functions and constants (
sin,cos,exp,pi, etc.). - Add robust input validation for expression,
x0, andh > 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
- Implement all three finite-difference formulas.
- Keep method selection explicit and testable.
- 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
- Compute
y0 = f(x0)and tangent equation using slopem. - Sample function curve across
[xmin, xmax]. - Plot function, marked point
(x0, y0), and local tangent segment.
Phase 4: Stability Diagnostics
- Add optional
hsweep mode. - Measure absolute difference to known derivative when available.
- Emit warning when estimates vary drastically for neighboring
hvalues.
Phase 5: Final Reporting
- Standardize textual output format.
- Save plot artifact with deterministic filename pattern.
- Include metadata banner in plot title (
method,h,x0).
Testing Strategy
Use deterministic test cases with clear tolerances.
Numeric Correctness Tests
- Polynomial baseline:
f(x)=x^2,x0=3- Expected derivative:
6 - Tolerance target with central difference and
h=1e-4:|estimate-6| < 1e-3
- Trigonometric baseline:
f(x)=sin(x),x0=1- Expected derivative:
cos(1)
- Exponential baseline:
f(x)=exp(x),x0=0- Expected derivative:
1
Stability Tests
hsweep for smooth function to show U-shaped error trend.- Non-differentiable point test:
f(x)=abs(x),x0=0- Tool should warn that derivative is method-dependent / unstable.
Output and UX Tests
- Missing argument handling returns clear error message.
- Invalid method or non-positive
hrejected. - Plot contains labeled legend entries for all drawn elements.
Common Pitfalls
- Tiny
hgives worse answers:- Cause: floating-point cancellation.
- Fix: test multiple
h; prefer central difference in a moderatehrange.
- Exploding values near discontinuity:
- Cause: function undefined near
x0. - Fix: pre-check domain and report invalid neighborhoods.
- Cause: function undefined near
- Tangent line looks “wrong”:
- Cause: displayed over too wide interval.
- Fix: restrict tangent drawing to local window around
x0.
- False confidence from one test:
- Cause: only validating on polynomials.
- Fix: include trig and exponential test suite.
Extensions
- Add second-derivative estimator to infer concavity.
- Implement secant-line animation converging to tangent line.
- Add automatic step-size suggestion based on local scale.
- Support piecewise functions with breakpoint annotations.
- Add batch mode to compute derivatives at multiple points and export CSV.
Real-World Connections
- Physics: velocity and acceleration from position-time data.
- Finance: marginal change of cost/revenue with respect to quantity.
- Biology: growth rate estimation from population measurements.
- 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:
- Why does central difference usually beat forward difference for smooth functions?
- What two errors compete when choosing
h? - Why can
f(x)=|x|atx=0produce conflicting derivative estimates? - How would you convince a classmate that derivative is local, not global?
- If your estimate changes from
4.8to12.1whenhchanges 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 (
hsweep or non-differentiable case). - Documents limitations and when derivative estimates should not be trusted.
- Provides sample run logs and generated plot artifacts.