Rob
Rob

Reputation: 11

Why do two methods of numpy array multiplication give different answers?

In this small example the two "res" variables give different results. Can someone explain why this is? I expect them to both return roughly 5.

import numpy as np
import matplotlib.pyplot as plt

dist1 = np.random.normal(100., 10., 10000)
dist2 = np.random.normal(0.05, 0.005, 10000)

res1 = dist1
res1 *= dist2

res2 = dist1 * dist2

print np.median(res1)
print np.median(res2)

# 4.986893617080765
# 0.24957162692779786

Upvotes: 0

Views: 57

Answers (1)

Bakuriu
Bakuriu

Reputation: 101939

res1 = dist1 does not copy dist1. You are modifying it in place with *= hence those are two different operations.

Use copy to copy the array:

>>> dist1 = np.random.normal(100., 10., 10000)
>>> dist2 = np.random.normal(0.05, 0.005, 10000)
>>> 
>>> res1 = dist1.copy()
>>> res1 *= dist2
>>> 
>>> res2 = dist1 * dist2
>>> 
>>> print(np.median(res1))
4.970902419879373
>>> print(np.median(res2))
4.970902419879373

Just a tip: "variables" in python are just names (i.e. references) for objects. They do not represent a memory location. So doing:

res1 = dist1

You are simply giving a new name to the object whose name is dist1 and now this object has two names (res1 and dist1) and can be accessed by both.

When the object is immutable the difference between names/references and values is hard to see, but the difference is fundamental when dealing with mutable objects.

Upvotes: 1

Related Questions