1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] The values ​obtained from calculations on Numpy and C are not equal

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024 às 01:52.

  1. Stack

    Stack Membro Participativo

    I tried writing a code to calculate a Numpy Array using C, made it lib.so, and tried to calculate a large Matrix. Then I tried to calculate using Numpy Python. It turned out that when I compared the values, they were not equal.

    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, :])



    and this is my C Code

    #include <stddef.h>

    // 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]);
    }
    }


    Compile

    gcc -shared -o example.so -fPIC module_vector.c


    I expect to gain knowledge and how to solve it correctly. Here is an example of my result.

    Time C : 0.05158950947225094
    Time Python : 0.05883005540817976
    [0.6418773 0.2731492 0.50642085]
    [0.6623829 0.2818951 0.4456129]

    Continue reading...

Compartilhe esta Página