Numerical Library#
Standard math functions are provided by the C++ numerics library which are accessed through
the <cmath> header.
This provides math functions like \(\sin(x)\)
Important
Trigonometric functions like \(\sin(x)\) expect their arguments to be in radians.
For raising numbers to a power, e.g., \(x**y\), we use the
std::pow() function. This differs a bit from some languages
which have an operator for exponentiation, like x**y.
Sine of angle in degrees#
Here’s an example of:
initializing an angle in degrees
converting the angle to radians
computing the sine of the angle in radians
#include <cmath>
#include <iostream>
#include <numbers>
int main() {
double angle_degrees{60.0};
double angle_radians = angle_degrees * std::numbers::pi / 180.0;
double sine_angle = std::sin(angle_radians);
std::cout << sine_angle << std::endl;
}
Powers#
#include <cmath>
#include <iostream>
int main() {
double x{2.0};
// compute x**3
std::cout << "x**3 = " << std::pow(x, 3.0) << std::endl;
std::cout << std::endl;
// compute x**0.5
std::cout << "x**0.5 = " << std::pow(x, 0.5) << std::endl;
std::cout << " = " << std::sqrt(x) << std::endl;
std::cout << std::endl;
// compute x**(1./3.)
std::cout << "x**(1./3.) = " << std::pow(x, 1.0 / 3.0) << std::endl;
std::cout << " = " << std::cbrt(x) << std::endl;
std::cout << std::endl;
}
Exponential and logs#
Important
std::log() is the natural logarithm. For common
logarithm (base-10), use std:log10().
#include <cmath>
#include <iostream>
int main() {
double x{123456.789};
double ln_x = std::log(x);
double log10_x = std::log10(x);
std::cout << "ln(x) = " << ln_x << std::endl;
std::cout << "log10(x) = " << log10_x << std::endl;
std::cout << std::endl;
// notice that we use { } here to "scope" this
// meaning that x_recovered is not defined outside
// of this block.
{
double x_recovered = std::exp(ln_x);
std::cout << "exp(ln(x)) = " << x_recovered << std::endl;
std::cout << "difference = " << x - x_recovered << std::endl;
std::cout << std::endl;
}
{
double x_recovered = std::pow(10.0, log10_x);
std::cout << "10**log10(x) = " << x_recovered << std::endl;
std::cout << "difference = " << x - x_recovered << std::endl;
std::cout << std::endl;
}
}
Absolute value#
Caution
You may see some examples on the internet that add the line
using namespace std;
and then access functions without the std:: namespace.
This can be dangerous, since you might not get the function you intend from the C++ standard library.
This can be especially dangerous with std:abs().
#include <cmath>
#include <iostream>
int main() {
double x{-1.234};
std::cout << "std::abs(x) = " << std::abs(x) << std::endl;
std::cout << "abs(x) = " << abs(x) << std::endl;
}