Значения, полученные в результате расчетов на Numpy и C, не равны ⇐ Python

Программы на Python
Anonymous
Значения, полученные в результате расчетов на Numpy и C, не равны

Сообщение Anonymous »

Я попробовал написать код для вычисления массива Numpy с использованием C, создал его lib.so и попытался вычислить большую матрицу. Затем я попытался посчитать с помощью Numpy Python. Оказалось, что когда я сравнил значения, они оказались не равными.
import ctypes
from ctypes import CDLL
from ctypes import c_size_t
import numpy as np
import time

# load the library
mylib = CDLL("example.so")

# C-type corresponding to numpy array for 3D arrays and 1D array
ND_POINTER_3 = np.ctypeslib.ndpointer(dtype=np.float32, ndim=3, flags="C_CONTIGUOUS")
ND_POINTER_1 = np.ctypeslib.ndpointer(dtype=np.float32, ndim=1, flags="C_CONTIGUOUS")

# define prototypes
mylib.add_vector.argtypes = [ND_POINTER_3, ND_POINTER_3, ND_POINTER_1, ND_POINTER_3, c_size_t]
mylib.add_vector.restype = ctypes.c_void_p

# Initialize numpy arrays (90x160x3 for la and lb, 90x160x1 for gm, and 90x160x3 for out)
np.random.seed(0)
la = np.random.rand(90, 160, 3).astype(np.float32)
lb = np.random.rand(90, 160, 3).astype(np.float32)
gm = np.random.rand(90, 160, 1).astype(np.float32)
out = np.zeros((90, 160, 3), dtype=np.float32)

# Flatten the gm array to pass as a 1D array
gm_flat = gm.flatten()

s = time.perf_counter()
for i in range(1000):
mylib.add_vector(la, lb, gm_flat, out, la.size)
out = np.array(out)
e = time.perf_counter()
print(f"Time C : {e-s}")

s = time.perf_counter()
for i in range(1000):
test_result = la * lb + la * (1.0 - la)
e = time.perf_counter()
print(f"Time Python : {e-s}")

print(out[0, 1, :])
print(test_result[0, 1, :])


и это мой код C
#include

// Add vector function that supports 3D arrays and 1D arrays
void add_vector(float *la, float *lb, float *gm, float *out, size_t size) {
for (size_t i = 0; i < size; ++i) {
// Perform element-wise operation: ls = la * gm + lb * (1.0 - gm)
size_t gm_index = (i / 3);
out = la * gm[gm_index] + lb * (1.0f - gm[gm_index]);
}
}

Компилировать
gcc -shared -o example.so -fPIC module_vector.c

Я рассчитываю получить знания и способы их правильного решения. Вот пример моего результата.
Time C : 0.05158950947225094
Time Python : 0.05883005540817976
[0.6418773 0.2731492 0.50642085]
[0.6623829 0.2818951 0.4456129]


Подробнее здесь: https://stackoverflow.com/questions/790 ... -not-equal

Вернуться в «Python»