Mentions légales du service

Skip to content
Snippets Groups Projects
Commit a6886d24 authored by FARNUDI Ali's avatar FARNUDI Ali
Browse files

Merge branch '1-define-a-function-to-take-a-numpy-array' into 'master'

Add C++ function to calculate sum of input vector

Closes #1

See merge request !2
parents e8a4b65a a80872fe
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,25 @@ 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;
}
double sum_2d_array(const std::vector<std::vector<double>> &arr) {
double sum = 0;
for (const auto &row : arr) {
for (double num : row) {
sum += num;
}
}
return sum;
}
namespace py = pybind11;
PYBIND11_MODULE(_core, m) {
......@@ -46,6 +66,9 @@ 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");
m.def("sum_2d_array", &sum_2d_array, "Calculate the sum of elements in a 2D 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,
sum_2d_array,
)
__all__ = ["__doc__", "__version__", "add", "subtract"]
__all__ = [
"__doc__",
"__version__",
"add",
"subtract",
"multiply",
"sum_array",
"sum_2d_array",
]
from __future__ import annotations
import pybind_example as m
import numpy as np
def test_version():
......@@ -13,3 +14,23 @@ def test_add():
def test_sub():
assert m.subtract(1, 2) == -1
def test_sum_array_numpy_array_1D_float():
array = np.asarray([1.0, 1.0, 2.0, 1.0, 1.0])
assert m.sum_array(array) == 6
def test_sum_array_numpy_list_1D_float():
list_ = [1.0, 1.0, 2.0, 1.0, 1.0]
assert m.sum_array(list_) == 6
def test_sum_array_numpy_array_1D_int():
array = np.ones(10)
assert m.sum_array(array) == 10
def test_sum_array_numpy_array_2D_float():
array = np.arange(9).reshape((3,3))
assert m.sum_2d_array(array) == np.sum(array)
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