Skip to content

mehedyk/Numerical-Analysis

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

42 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Typing SVG
Numerical Analysis Workbench Banner



HTML5 JavaScript Math.js Mobile Ready No Build Step Security License: MIT


A beautiful, interactive, zero-dependency workbench for solving equations using Bracketing Methods.
Designed for Numerical Analysis students — type any equation, watch the algorithm converge in real time, and export a print-ready report in one tap.
Supports Bisection and False Position methods, with Newton–Raphson and more on the way.



📸 Screenshots

Desktop View Solution + IVT Check
Desktop Solution
Bisection Graph Iteration Table
Graph Table
Mobile Portrait Exported PDF
Mobile Export

📋 Table of Contents


✨ Features

🔢 Feature Description
🎯 Smart Auto-Bracket Detection Automatically scans 0 → +1000 first for a positive bracket, then falls back to −1000 → 0 — so functions like 1-x·cos(x) land on [4, 5] not [-3, -2]. A "prefer negative" toggle reverses the priority when you need it.
✍️ Natural Equation Input Type equations the way you write them: xtan(x)-1, lnx-cosx, 3x^3-7x+5 — the smart preprocessor handles implicit multiplication and bare-function notation
🔀 Two Bracketing Methods Switch between Bisection (always halves) and False Position (secant-line intercept) from the sheet index — same inputs, same table, different formula for c
🎞️ Animated Graph Watch the bracket narrow in real time with a built-in step player — go forward, back, or let it play automatically
📊 Full Iteration Table Every column: n, a, b, f(a), f(b), c, f(c), Absolute Error, Relative Error
IVT Verification Automatically verifies the Intermediate Value Theorem condition f(a)·f(b) < 0 before solving
🛑 Flexible Stop Criteria Default: stops as soon as two consecutive c values look identical at the chosen precision — fast and intuitive. Also supports fixed iteration count, custom tolerance ε, and a legacy full-precision mode
🌍 True Root Mode Provide the known true root to get exact absolute and relative errors per iteration
📥 One-Tap Export Download a full landscape PNG image or multi-page PDF — works perfectly on mobile too
📱 Mobile-First Design 44px touch targets, stacked layouts, portrait-safe export — built for phones first
🔐 Security Hardened CSP headers, XSS-safe rendering, input length limits, MIME validation, whitelisted radio values
💡 10 Built-in Examples From simple cubics to transcendental equations — great for testing and learning

📐 How the Bisection Method Works

The Bisection Method (also called the binary search method for roots) is a bracketing algorithm that repeatedly halves an interval until the root is isolated to within a desired tolerance.

Prerequisites — The Intermediate Value Theorem

If $f$ is continuous on $[a, b]$ and $f(a) \cdot f(b) &lt; 0$, then by the IVT there exists at least one root $c \in (a, b)$.

Algorithm

Given: f(x), bracket [a, b] where f(a)·f(b) < 0

Repeat:
  1. c  ←  (a + b) / 2          ← midpoint
  2. if f(c) = 0 → root found!
  3. if f(a)·f(c) < 0 → b ← c   ← root in left half
  4. else            → a ← c    ← root in right half
  5. until c stops changing  (or max iterations reached)

Convergence

Each iteration halves the bracket, so after $n$ steps:

$$|c_n - r| \leq \frac{b - a}{2^n}$$

To guarantee $k$ correct decimal places, you need at least:

$$n \geq \frac{\log_{10}(b-a) - \log_{10}(\varepsilon)}{\log_{10}(2)} \approx 3.32 \cdot \log_{10}!\left(\frac{b-a}{\varepsilon}\right) \text{ iterations}$$

Worked Example — cos(x) − x = 0

Step a b c = (a+b)/2 f(c) New bracket
1 0.0000 1.0000 0.5000 +0.3776 [0.5, 1.0]
2 0.5000 1.0000 0.7500 −0.0183 [0.5, 0.75]
3 0.5000 0.7500 0.6250 +0.1860 [0.625, 0.75]
4 0.6250 0.7500 0.6875 +0.0838 [0.6875, 0.75]
5 0.6875 0.7500 0.7188 +0.0327 [0.7188, 0.75]
14 0.7391 0.7391 0.7391 ≈ 0 ✅ c repeated — converged

Root: $x \approx 0.7390851332$

At 4 decimal places the solver stops around step 14 once c stabilises to 0.7391. Switch to the Full machine precision stop mode if you need all 52 steps.


🧮 Built-in Equation Examples

The app ships with 10 ready-to-solve equations accessible from the Examples panel. Click any row to load it instantly.

📂 View All 10 Examples

1 · Classic Cubic

$$f(x) = x^3 - x - 2 = 0$$ Bracket: $[1,\ 2]$  ·  Root: $x \approx 1.5214$

f(1) = -2  < 0
f(2) = +4  > 0  ✓ IVT satisfied

2 · Cubic — Two Positive Coefficients

$$f(x) = x^3 - 4x - 9 = 0$$ Bracket: $[2,\ 3]$  ·  Root: $x \approx 2.7065$


3 · Cubic with Negative Root ⭐ New

$$f(x) = 3x^3 - 7x + 5 = 0$$ Bracket: $[-2,\ -1]$  ·  Root: $x \approx -1.8340$

Requires a negative bracket — enter manually as a = -2, b = -1, or enable "Prefer negative x range" in auto-detect mode.

f(−2) = −5  < 0
f(−1) = +9  > 0  ✓ IVT satisfied

4 · Transcendental (Trig)

$$f(x) = \cos(x) - x = 0$$ Bracket: $[0,\ 1]$  ·  Root: $x \approx 0.7391$ (the Dottie number)


5 · Exponential

$$f(x) = e^x - 3x = 0$$ Bracket: $[0,\ 1]$  ·  Root: $x \approx 0.6190$


6 · Square Root of 2

$$f(x) = x^2 - 2 = 0$$ Bracket: $[1,\ 2]$  ·  Root: $x \approx 1.4142 = \sqrt{2}$

Classic benchmark — converges to $\sqrt{2}$ with no floating-point tricks.


7 · Sine

$$f(x) = \sin(x) - \tfrac{x}{2} = 0$$ Bracket: $[1,\ 2]$  ·  Root: $x \approx 1.8955$


8 · x · tan(x) ⭐ New

$$f(x) = x\tan(x) - 1 = 0$$ Bracket: $[0,\ 1]$  ·  Root: $x \approx 0.8603$

You can type this as xtan(x)-1 — the app auto-inserts the *.


9 · Natural Log vs Cosine

$$f(x) = \ln(x) - \cos(x) = 0$$ Bracket: $[1,\ 2]$  ·  Root: $x \approx 1.3029$

Type as ln(x)-cos(x) or shorthand lnx-cosx. Note: in this app ln(x) is always the natural log and log(x) is always base-10.


10 · Mixed Exponential

$$f(x) = e^x - x^2 - 2 = 0$$ Bracket: $[0,\ 1]$  ·  Root: $x \approx 0.4428$

Uses the e constant: type e^x - x^2 - 2.


⌨️ Equation Syntax Guide

You can type equations naturally — the input parser handles many common shorthand notations automatically.

Supported Notation

Math Type this Notes
$x^3$ x^3 Power operator
$3x^2$ 3x^2 or 3*x^2 Implicit coefficient multiply
$\sqrt{x}$ sqrt(x) Square root
$e^x$ e^x or exp(x) Euler's number
$\ln(x)$ ln(x) or lnx Natural log — use ln, not log
$\log_{10}(x)$ log(x) or log10(x) or logx Base-10 log
$\sin(x)$ sin(x) Trig functions
$x\tan(x)$ x*tan(x) or xtan(x) ⭐ Implicit multiply before function
$\cos(x)$ cos(x) or cosx ⭐ Bare-variable function shorthand
$\pi$ pi Pi constant
$e$ e Euler's number as constant
$ x $

⚠️ ln vs log — this parser deliberately separates them: ln(x) is always the natural log, log(x) is always base-10 (same as log10(x)). This matches how most Numerical Analysis textbooks write it.

⭐ Smart Preprocessor — Examples

The app runs a two-step preprocessor before evaluating, so these all work:

Input            →  Parsed as
─────────────────────────────────
xtan(x)-1        →  x*tan(x)-1
2sin(x)+cos(x)   →  2*sin(x)+cos(x)
lnx-cosx         →  ln(x)-cos(x)   (natural log)
logx-cosx        →  log10(x)-cos(x) (base-10 log)
sinx^2           →  sin(x)^2
log10x           →  log10(x)
3x^3-7x+5        →  3*x^3-7*x+5   (mathjs implicit multiply)

Bounds (a and b)

Bounds accept the same math expressions:

pi        →  3.14159…
2*pi      →  6.28318…
sqrt(2)   →  1.41421…
e         →  2.71828…
-2        →  −2  (negative bounds fully supported ✓)

🚀 Getting Started

How to Use the App

Step 1 ── Enter f(x)
          Type your equation, e.g.  cos(x) - x
          The validation dot turns green when the syntax is valid ●

Step 2 ── Choose bracket mode
          ○ Auto-detect       → scans positive x first (0 → +1000),
                                falls back to negative if nothing found.
                                Two optional sub-toggles:
                                  ☐ Prefer tighter decimal bracket
                                  ☐ Prefer negative x range (scan − side first)
          ○ Set a and b myself → type your own bounds (decimals, pi, -2, etc.)

Step 3 ── Set stop criterion (optional)
          ● When c stops changing  → DEFAULT — stops as soon as two consecutive
                                     midpoints display the same value at the
                                     chosen precision (typically ~13–20 steps)
          ○ Iterations             → exactly N steps
          ○ Tolerance ε            → stops when AE ≤ ε
          ○ Full machine precision → legacy mode, runs until bracket width
                                     < 4 × machine epsilon (~50 steps)

Step 4 ── Click SOLVE
          The IVT check, full iteration table, and graph all appear instantly.

Step 5 ── Animate (optional)
          Use ◀ ▶ buttons or ▷ Play to step through the algorithm visually.

Step 6 ── Export
          Tap "Download as image" or "Download as PDF" for a landscape report.

📱 Mobile Ready

The app is designed with mobile-first principles:

Mobile View

  • 44px minimum touch targets on all interactive elements (WCAG 2.5.5)
  • Stacked export buttons — full-width, easy to tap
  • IVT rows collapse vertically so nothing overflows on narrow screens
  • 2-column reading grid instead of a long horizontal strip
  • Hero diagram hidden on very small phones to save space
  • Mobile navigation bar for jumping between app sections
  • Touch-friendly table — scrolls horizontally with momentum

Export on Mobile

On a phone, the iteration table is clipped inside a scroll container. Standard screen-capture approaches would produce a narrow portrait image missing most columns.

This app solves that by building a dedicated off-screen 1120px landscape panel at capture time — the exported PNG/PDF is always full landscape with every column visible, regardless of what your device screen size is.


📥 Export Feature

After solving, tap either export button to download a complete, print-ready report.

Exported PDF example

The exported file includes:

Section Content
Header Equation, date, root approximation, iteration count, stop reason
IVT Banner f(a) and f(b) values, sign check confirmation
Iteration Table All columns: n, a, b, f(a), f(b), c, f(c), AE, RE
Footer Note Error formula used (bound or true root)
Credit Line Author + generation date

PNG — Landscape, 2× scale (retina quality), ~1120×auto px
PDF — Landscape A4, auto multi-page if the table is very long


🔒 Security

This is a client-side math tool. No data is ever sent to any server. The following hardening has been applied:

Layer Implementation
Content Security Policy <meta http-equiv="Content-Security-Policy"> — blocks scripts/frames from unknown origins
X-Content-Type-Options nosniff — prevents MIME-type sniffing attacks
Referrer Policy no-referrer — no URL leakage on external links
XSS Prevention All user-supplied strings are passed through escHtml() before any innerHTML insertion. Escapes &, <, >, ", '
Input Length Limits f(x) capped at 500 characters; bound expressions capped at 200 characters — prevents ReDoS on the regex preprocessor
Radio Button Whitelisting bracketMode and stopMode values are checked against explicit allowlists before use — cannot be injected
parseVal Guard Strings over 200 chars are rejected before reaching math.evaluate()
Download MIME Validation dl() validates blob type is image/png or application/pdf before creating the anchor
Filename Sanitisation Downloaded filenames are stripped of unsafe characters via regex
SQL Injection Not applicable — this is a fully client-side application with no database or backend
Sandboxed Math Eval All expression evaluation is done via Math.js which provides its own sandboxed parser — eval() is never called on user input

🛠 Tech Stack

Library Version Purpose
Math.js 14.x Expression parsing & sandboxed evaluation
html2canvas 1.4.1 DOM → Canvas for image export
jsPDF 3.0.3 Canvas → PDF export
IBM Plex Sans / Mono Typography (Google Fonts)

Zero build tooling. No Webpack, Vite, Rollup, npm, or Node.js required. All libraries are loaded from cdnjs.cloudflare.com.


📁 Project Structure

numerical-analysis-workbench/
│
├── index.html              ← page markup & layout
├── styles.css              ← all styling (design tokens, components, responsive)
├── core.js                 ← shared math utilities, export plumbing, page chrome
├── engine-bracketing.js    ← Bisection & False Position engines, graph, table
├── concern.html            ← Academic Integrity & Usage Policy page
├── favicon.svg             ← browser tab icon
│
└── assets/
    ├── banner.svg
    └── screenshots/
        ├── 01-desktop-full.png
        ├── 02-solution-ivt.png
        ├── 03-graph-step4.png
        ├── 04-iteration-table.png
        ├── 05-mobile.png
        └── 06-export-pdf.png

The app is zero-dependency static files — no build step, no npm, no server. Drop the folder anywhere and open index.html.


🙋 FAQ

Why did the solver stop after only ~13 steps?
That's the new default behaviour — "When c stops changing". The solver compares consecutive midpoints at your chosen decimal precision (default: 4 places). Once two consecutive steps show the exact same displayed value, the root is resolved to that precision and there's nothing left to narrow.

This is mathematically correct: if c looks the same in two rows, you have your answer to the digits you can see.

If you need more steps — for a class assignment that asks for exactly N iterations, or to see the full convergence trail — switch the stop criterion to "A fixed number of steps" or "Full machine precision" before clicking Solve.

Why does my equation show a red dot?
The validation dot turns red when Math.js cannot parse the expression. Common fixes:
  • Use * for multiplication: 2*x not 2 x (space alone won't work)
  • Use ^ for powers: x^3 not
  • Functions need parentheses: sin(x) not sin x — or use the shorthand sinx
  • Division: x/2 not x÷2
  • Natural log: use ln(x)log(x) is base-10 in this app
Why does auto-detect sometimes not find a bracket?
The scanner checks whole-number steps from 0 to +1000 (positive pass), then −1000 to 0 (negative fallback). It will fail if:
  1. The function has no real roots in that range
  2. The root is at a discontinuity (e.g. tan(x) has sign changes at asymptotes that look like roots)
  3. The function requires a very small bracket that the whole-number scan skips over

Switch to "I'll set a and b myself" and enter bounds you know contain a root.

Auto-detect keeps returning a positive bracket — I need a negative one
By design, the scanner tries positive x values first. To force it to prefer the negative side, tick "Prefer negative x range" under the auto-detect option before clicking Solve. The scanner will then complete the negative sweep first and return the smallest-magnitude negative bracket it finds.
Can I use negative values for a and b?
Yes! Negative bounds are fully supported in manual mode. Just type `-2` for `a` and `-1` for `b`. The example `3x^3 - 7x + 5` uses `[-2, -1]` because its only real root is ≈ −1.834.
What's the difference between AE and RE in the table?
  • AE (Absolute Error): If you provided a true root → |c − true_root|. Otherwise → (b − a) / 2 (the guaranteed error bound from the bracket width).
  • RE (Relative Error): AE / |c| — gives the error as a fraction of the approximation.
The export looks different on my phone vs desktop — is that normal?
The app UI adapts for mobile screens. However, the exported file is always identical — it's rendered from a dedicated off-screen 1120px landscape panel, not a screenshot of what you see on screen. So the PDF/PNG will always contain every column in landscape format regardless of your device.
Can I host this on my own domain?
Absolutely. Upload all the root-level files together to any static host:
index.html  styles.css  core.js  engine-bracketing.js  concern.html  favicon.svg
  • GitHub Pages (free)
  • Netlify (free, drag-and-drop)
  • Vercel (free)
  • Any shared hosting with FTP access

📊 Algorithm Complexity

Property Value
Convergence Linear — guaranteed
Error after n steps $\leq (b-a) / 2^n$
Steps for 6 decimal places $\approx 20$ iterations (starting from bracket width 1)
Steps for 10 decimal places $\approx 34$ iterations
Failure conditions f not continuous on [a,b], or f(a)·f(b) ≥ 0
Compared to Newton-Raphson Slower but always converges; no derivative needed
Compared to False Position More predictable step count; False Position is often faster but can stagnate on one-sided curves

🤝 Contributing

Contributions are welcome! Here's how:

# 1. Fork and clone
git clone https://github.com/mehedyk/Numerical-Analysis.git

# 2. Create a feature branch
git checkout -b feature/my-new-method

# 3. Make your changes
#    - New methods go in engine-*.js (see engine-bracketing.js as a template)
#    - Shared utilities go in core.js
#    - UI/layout changes go in index.html + styles.css

# 4. Test by opening index.html in a browser (no build needed)

# 5. Submit a pull request

Ideas for Contributions

  • False Position method ✓
  • Newton–Raphson method
  • Secant method
  • Fixed-point iteration
  • Lagrange interpolation
  • Dark/light theme toggle
  • Share-by-URL (encode equation in URL hash)
  • Copy table as LaTeX / CSV
  • Complex root detection warning
  • Bangla language support 🇧🇩

📝 License

MIT License

Copyright (c) 2026 S.M. Mehedy Kawser

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

Footer



GitHub stars GitHub forks


If this helped you pass your Numerical Analysis exam — leave a ⭐

Releases

No releases published

Packages

 
 
 

Contributors