Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

3.9 Math

Like C, C++ wasn't designed primarily with numerical computation in mind. However, a lot of numerical work is done in C++, and the standard library reflects that.

3.9.1 Complex Numbers

The standard library supports a family of complex number types along the lines of the complex class described in Chapter 2. To support complex numbers where the scalars are single-precision, floating-point numbers (floats), double precision numbers (doubles), and so on, the standard library complex is a template:

template<class scalar> class complex {
public:
  complex(scalar re, scalar im) ;
  // ...
};

The usual arithmetic operations and the most common mathematical functions are supported for complex numbers. For example:

// standard exponentiation function from _complex_:
template<class C> complex<C> pow(const complex<C>&, int) ;

void f(complex<float> fl, complex<double> db)
{
  complex<long double> ld = fl+sqrt(db) ;
  db += fl*3;
  fl = pow(1/fl,2) ;
  // ...
}

3.9.2 Vector Arithmetic

The vector described in §3.7.1 was designed to be a general mechanism for holding values, to be flexible, and to fit into the architecture of containers, iterators, and algorithms. However, it does not support mathematical vector operations. Adding such operations to vector would be easy, but its generality and flexibility precludes optimizations that are often considered essential for serious numerical work. Consequently, the standard library provides a vector, called valarray, that is less general and more amenable to optimization for numerical computation:

template<class T> class valarray {
  // ...
  T& operator[](size_t) ;
  // ...
};

The type size_t is the unsigned integer type that the implementation uses for array indices.

The usual arithmetic operations and the most common mathematical functions are supported for valarrays. For example:

// standard absolute value function from _valarray_:
template<class T> valarray<T> abs(const valarray<T>&) ;

void f(valarray<double>& a1, valarray<double>& a2)
{
  valarray<double> a = a1*3.14+a2/a1;
  a2 += a1*3.14;
  a = abs(a) ;
  double d = a2[7] ;
  // ...
}

3.9.3 Basic Numeric Support

Naturally, the standard library contains the most common mathematical functions—such as log(), pow(), and cos(). In addition, classes that describe the properties of built-in types—such as the maximum exponent of a float—are provided.

  • + Share This
  • 🔖 Save To Your Account