Mentions légales du service

Skip to content
Snippets Groups Projects
Commit 1a78e32e authored by ali's avatar ali
Browse files

Add C++ function to calculate sum of input vector

Works with both numpy arrays and lists on the python side
parent e8a4b65a
No related branches found
No related tags found
1 merge request!2Add C++ function to calculate sum of input vector
#include <pybind11/pybind11.h>
#include <pybind11/stl.h> // This header is needed to work with STL containers like std::vector
// #define VERSION_INFO 1.0
......@@ -13,6 +14,15 @@ double multiply(double i, double j) {
return i * j;
}
double sum_array(const std::vector<double> &arr) {
double sum = 0;
for (double num : arr) {
sum += num;
}
return sum;
}
namespace py = pybind11;
PYBIND11_MODULE(_core, m) {
......@@ -46,6 +56,8 @@ PYBIND11_MODULE(_core, m) {
Some other explanation about the subtract function.
)pbdoc",py::arg("i"), py::arg("j"));
m.def("sum_array", &sum_array, "Calculate the sum of elements in an array");
#ifdef VERSION_INFO
m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO);
#else
......
from __future__ import annotations
from ._core import __doc__, __version__, add, subtract, multiply
from ._core import __doc__, __version__, add, subtract, multiply, sum_array
__all__ = ["__doc__", "__version__", "add", "subtract"]
from __future__ import annotations
import pybind_example as m
import numpy as np
def test_version():
assert m.__version__ == "0.0.1"
......@@ -13,3 +13,12 @@ def test_add():
def test_sub():
assert m.subtract(1, 2) == -1
def test_sum_array_numpy_array_1D():
array = np.asarray([1.,1.,2.,1.,1.])
assert m.sum_array(array) == 6
def test_sum_array_numpy_list_1D():
list_ = [1.,1.,2.,1.,1.]
assert m.sum_array(list_) == 6
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment