Skip to content
The site is in test mode. All features are free for now.
MathAgora

C++ and Mathematics

Numerical methods

Floating-point precision, <cmath>, Newton's method, bisection, numerical integration and series approximations.

60 min 8 questions

01Floating point and `<cmath>`

A double stores a number in binary with about 15–16 significant digits, so 0.10.1 is not represented exactly and 0.1 + 0.2 == 0.3 is false. Compare floating-point values with a tolerance: fabs(a - b) < 1e-9.

<cmath>: sqrt, pow, fabs, floor (round down), ceil (round up), exp, log (natural), sin, cos.

02Finding roots of equations

Bisection: if ff is continuous and f(a)f(a), f(b)f(b) have opposite signs, there is a root in [a,b][a, b] (Intermediate Value Theorem). Each step takes the midpoint mm and keeps the half where the sign changes — the interval halves.

Newton's method: xn+1=xn−f(xn)f′(xn)x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}. For f(x)=x2−2f(x) = x^2 - 2 this becomes xn+1=12(xn+2xn)x_{n+1} = \frac12\left(x_n + \frac{2}{x_n}\right) — it converges very fast (the correct digits of 2\sqrt2 roughly double each step).

C++
double x = 1;
for (int i = 0; i < 5; i++)
    x = (x + 2 / x) / 2;      // Newton's method for sqrt(2)

03Integrals and series

Trapezoidal rule: ∫abf≈h2[f(x0)+2f(x1)+⋯+2f(xn−1)+f(xn)]\int_a^b f \approx \frac h2\left[f(x_0) + 2f(x_1) + \dots + 2f(x_{n-1}) + f(x_n)\right], h=b−anh = \frac{b - a}{n}. As nn grows the error shrinks roughly like 1n2\frac{1}{n^2}.

Series: e=∑k=0∞1k!e = \sum_{k=0}^\infty\frac{1}{k!}. In code, update the term at each step (term /= k) instead of recomputing the factorial.

Key formulas

  • Comparing floating-point numbers

    ∣a−b∣<ε|a-b|<\varepsilon
  • Newton's method

    xn+1=xn−f(xn)f′(xn)x_{n+1}=x_n-\dfrac{f(x_n)}{f'(x_n)}
  • Trapezoidal rule

    ∫abf≈h2[f0+2f1+⋯+2fn−1+fn]\int_a^b f\approx\tfrac h2\big[f_0+2f_1+\dots+2f_{n-1}+f_n\big]
  • ee as a series

    e=∑k=0∞1k!e=\sum_{k=0}^\infty\dfrac1{k!}

Worked examples

Example 1

Write a function that finds the root of x2=2x^2 = 2 on [1,2][1, 2] by bisection to within 10−610^{-6}.

C++
double lo = 1, hi = 2;
while (hi - lo > 1e-6) {
    double m = (lo + hi) / 2;
    if (m * m - 2 > 0) hi = m;   // root is to the left
    else lo = m;
}
cout << lo;                       // 1.41421