Monday 15 February 2010

python - Numpy, why does `x += y` produce a different result than `x = x + y`? -


This question and an answer is already here is:

  • 2 Responses

    in this case, Why does x + = y produce a different result compared to x = x + y ?

      import numpy NP as X = np.repeat ([1], 10) y = np.random.random (len (x)) x + = y print x # Output: [1 1 1 1 1 1 1 1 1 1 1] x = x + y print x # output: [1.50859536 1.31434732 1.15147365 1.76979431 1.64727364 # 1.02372535 1.39335253 1.71878847 1.48823703 1.99458116]    

    explains questions linked although general issue, the figures for this particular case-specific interpretation. Actually, those answers say that "it depends on the type of cover", and what I'm giving down is the interpretation for the numpy type.

    When you do is x + y , uses a "lowest common denominator" datatype for results Results Since x int and y is float, that means it gives a float array.

    But when you are complying with x + = y , you have to comply with the dtype of x , which is the int It reduces the decimal part and leaves all x values ​​back to 1. In this way, the fake enhanced assignment defines operators: This assignment emphasizes the same type of return value as the goal.

    You can do x = (x + y) with another example. Sweetpe (int) (obviously forcing dtype back int) you can get second behavior from the first instance by x = np.repeat ([1.0], 10) (Using a boat is x , dtype is a boat, so you can now add it to y without tampering).

No comments:

Post a Comment