pybind11
pybind11 copied to clipboard
[BUG]: problem with python and c++ data type conversion
Required prerequisites
- [X] Make sure you've read the documentation. Your issue may be addressed there.
- [X] Search the issue tracker and Discussions to verify that this hasn't already been reported. +1 or comment there if it has.
- [X] Consider asking first in the Gitter chat room or in a Discussion.
What version (or hash if on master) of pybind11 are you using?
2.10.4
Problem description
I try to create an ndarray(whose size is 5, and dtype is float) in c++ interface as the return value, which will be passed to a python function as output.
I tried this ↓
and this ↓
But all the methods turns out that the python function output data only retains one digit after the decimal point, which does not match the precision of float. For example: the return_data[0]=0.0025783 but the arr[0]=0.0
Where did I make a mistake? Anyone gets any ideas??
Reproducible example code
No response
Is this a regression? Put the last known working version here if it is.
Not a regression
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
py::array_t<float> create_array() {
// Create a NumPy array with 5 elements, dtype=float
py::array_t<float> arr(5); // 5 elements, float dtype
// Access the data buffer and set the values
auto buf = arr.request();
float* ptr = static_cast<float*>(buf.ptr);
// Assign values with high precision
ptr[0] = 0.0025783f;
ptr[1] = 1.2345678f;
ptr[2] = 3.1415926f;
ptr[3] = 2.7182818f;
ptr[4] = 1.6180339f;
return arr;
}
PYBIND11_MODULE(example, m) {
m.def("create_array", &create_array, "Create an array of floats with high precision");
}