Vectoring a C++ Function

We can use pybind11 to convert a C++ function that takes scalars to work with NumPy arrays as input. This uses the py::vectorize functionality in pybind11.

Here’s the same simple function as before, but now we simply pass the function into the pybind11 macros as pybind11::vectorize(f):

Listing 153 vectorize.cpp
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

#include <cmath>

double f(double x) {
    return std::sin(x);
}

PYBIND11_MODULE(vectorize, m) {
    m.doc() = "simple example of creating a function f(x) in C++";
    m.def("f", pybind11::vectorize(f));
}

Here’s a driver:

Listing 154 test_vectorize.py
import numpy as np

import vectorize

a = np.linspace(0, 2.0 * np.pi, 16)

print(vectorize.f(a))