为什么numpy数组乘法的两种方法给出不同的答案?

2024-06-11 21:56:12 发布

您现在位置:Python中文网/ 问答频道 /正文

在这个小例子中,两个“res”变量给出了不同的结果。有人能解释这是为什么吗?我预计他们都会返回大约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

Tags: importnumpymatplotlibasnpresrandom例子
1条回答
网友
1楼 · 发布于 2024-06-11 21:56:12

res1 = dist1不复制dist1。您正在用*=就地修改它,因此这是两种不同的操作

使用copy复制数组:

>>> 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

提示:python中的“变量”只是对象的名称(即引用)。它们不代表记忆位置。这样做:

res1 = dist1

您只需给名为dist1的对象赋予一个新名称,现在这个对象有两个名称(res1dist1),并且两个名称都可以访问

当对象是不可变的时,很难看到名称/引用和值之间的差异,但在处理可变对象时,这种差异是根本性的

相关问题 更多 >