[Python] NumPy array assignment gives different result from direct computation despite...

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    Problem Description


    I'm performing linear interpolation between two arrays x1 and x2 using weights i/N. The calculation is mathematically simple:

    x = (1 - i/N) * x1 + (i/N) * x2


    However, when I compare the assigned x with the same formula computed directly in print(), the results differ significantly (e.g., 0.0196 vs 0.02). This contradicts both mathematical equivalence and floating-point error expectations.

    Minimal Reproducible Example


    import numpy as np

    x1 = np.arange(0, 0.5, 0.01) # 0 to 0.49
    x2 = np.arange(0.5, 1, 0.01) # 0.5 to 0.99
    x = np.zeros_like(x1)
    y = x # Shared memory (intentional? bug?)

    N = x1.size
    for i in range(N):
    x = (1 - i/N) * x1 + (i/N) * x2
    print(
    f"i={i:2d} | weight={i/N:.4f} | "
    f"theory: {(1-i/N)*x1 + (i/N)*x2:.6f} | "
    f"assigned x: {x:.6f}"
    )

    Actual Output


    0 0 0 0 0 0
    1 0.02 0.0098 0.0102 0.0196 0.02
    2 0.04 0.0192 0.0208 0.0384 0.04
    3 0.06 0.0282 0.0318 0.0564 0.06
    4 0.08 0.0368 0.0432 0.0736 0.08
    5 0.1 0.045 0.055 0.09 0.1
    6 0.12 0.0528 0.0672 0.106 0.12
    7 0.14 0.0602 0.0798 0.12 0.14
    ...
    46 0.92 0.0368 0.883 0.0736 0.92
    47 0.94 0.0282 0.912 0.0564 0.94
    48 0.96 0.0192 0.941 0.0384 0.96
    49 0.98 0.0098 0.97 0.0196 0.98


    Discrepancy grows with i!

    What I've Checked

    1. Floating-point precision: Used %.6f to rule out display rounding.
    2. Array independence: Initially suspected y = x causing interference, but even removing y assignment doesn't fix it.
    Question


    Why does the assigned value x differ from the direct computation of the same formula?

    • Is this a NumPy-specific behavior?
    • Could it be due to memory allocation or implicit type conversion?

    Continue reading...

Compartilhe esta Página