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 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 is continuous and , have opposite signs, there is a root in (Intermediate Value Theorem). Each step takes the midpoint and keeps the half where the sign changes — the interval halves.
Newton's method: . For this becomes — it converges very fast (the correct digits of roughly double each step).
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: , . As grows the error shrinks roughly like .
Series: . In code, update the term at each step (term /= k) instead of recomputing the factorial.
Key formulas
Comparing floating-point numbers
Newton's method
Trapezoidal rule
as a series
Worked examples
Example 1
Write a function that finds the root of on by bisection to within .
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.41421What does this code print? (true prints as 1, false as 0)
#include <iostream>
using namespace std;
int main() {
cout << (0.1 + 0.2 == 0.3);
}Sample content: questions and lessons are illustrative and are not taken from official exams.
