I am trying to pass arrays to a c++ function from a python driver. One of the arrays I am passing to the c++ function is a results array. I know the data is passing to the code correctly, but seems to be truncating on the way back. I'm loosing my precision after the decimal. Any ideas where I went wrong? Below is a simplified version of the code, and the resultant output.
python code:
import ctypes
from ctypes import *
def get_calculate_windows():
dll = ctypes.CDLL('./cppFunctions.so', mode=ctypes.RTLD_GLOBAL)
func = dll.calculate_windows
func.argtypes = [POINTER(c_float), POINTER(c_float), c_size_t]
return func
def calculate_windows(data, answer, size):
data_p = data.ctypes.data_as(POINTER(c_float))
answer_p = answer.ctypes.data_as(POINTER(c_float))
__calculate_windows(data_p, answer_p, size)
###### MAIN FUNCTION #####
data = np.array(myData, dtype=np.float32)
ans = np.array(myAnswer, dtype=np.float32)
print ans[:10]
calculate_windows(data, ans, myLength)
print ans[:10]
c++ code:
extern "C" {
void calculate_windows(float *h_data, float *result, size_t size ) {
for (int i=0; i<size; i++ ) {
result[i]=i/10;
}
}
}
output:
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
What the output SHOULD be:
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
I know the data is passing to the code correctly, but seems to be truncating on the way back. I'm losing my precision after the decimal. Any ideas where I went wrong?
You are using integer division instead of floating-point division.
You can fix this by using:
result[i] = i / 10.;
Instead of:
result[i] = i / 10;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.