我的问题的小介绍。
我想用numpy在dB中绘制一个声音文件。因为负数,仅仅做20 * np.log10(arr)
是不起作用的。
所以我在考虑使用np.where()
。因为np.where()
是ufunc
的一部分,所以我只想这样做(比使用括号更容易阅读)
我在这方面遇到了一些困难(通过一个小的随机数测试得到了意想不到的结果)。所以我更新到了numpy的最新版本(以前是1.18.x,现在是1.19.1)。
我还将Spyder更新为4.1.4
因此,我在控制台中执行以下步骤进行检查。 我还为一些步骤添加了注释
In [1]: import numpy as np
In [2]: a = np.round(np.random.rand(10) * 3, 0)
In [3]: a
Out[3]: array([2., 1., 2., 1., 1., 3., 2., 0., 2., 1.])
In [4]: tf = np.where(a==2, True, False)
In [5]: b = np.power(a,3, where=np.where(a==2, True, False))
In [6]: b
Out[6]:
array([8. , 1.42180731, 8. , 1.31799691, 1.01436297,
2.82985094, 8. , 0.35036821, 8. , 0.73520376])
In [7]: np.power(a,3, where=tf)
Out[7]: array([8., 1., 8., 1., 1., 3., 8., 0., 8., 1.])
In[8]: np.power(a,3, where=np.where(a==2, True, False))
Out[8]: array([8., 1., 8., 1., 1., 3., 8., 0., 8., 1.])
因此,当在控制台中进行计算时,它看起来很好,但当使用变量时,原始值会出错
In[9]: b=np.power(a,3, where=tf)
In[10]: b
Out[10]:
array([8. , 1.42180731, 8. , 1.31799691, 1.01436297,
2.82985094, 8. , 0.35036821, 8. , 0.73520376])
In[11]: np.log10(a, where=np.where(a>2, True, False))
Out[11]:
array([8. , 1.42180731, 8. , 1.31799691, 1.01436297,
0.47712125, 8. , 0.35036821, 8. , 0.73520376])
由于奇怪的结果,我检查了a
是否仍然正确
In[12]: a # Check if a still right
Out[12]: array([2., 1., 2., 1., 1., 3., 2., 0., 2., 1.])
看起来是的。所以我下一步就尝试了。检查发生了什么:
In[13]: np.log10(a, where=np.where(a>2, True, False))
Out[13]:
array([2. , 1. , 2. , 1. , 1. ,
0.47712125, 2. , 0. , 2. , 1. ])
In[14]: c = np.log10(a, where=np.where(a>2, True, False))
In[15]: c
Out[15]:
array([2. , 1. , 2. , 1. , 1. ,
0.47712125, 2. , 0. , 2. , 1. ])
不知何故,在c
(log10)的帮助下,一切正常。所以我删除了b(我使用spyder,所以我从变量浏览器中删除了它)。
然后我重新创建了b
In[16]: b = np.power(a, 3, where=np.where(a==2, True, False))
In[17]: b
Out[17]: array([8., 1., 8., 1., 1., 3., 8., 0., 8., 1.])
In[18]: b1 = np.power(a, 3, where=tf)
In[19]: b1
Out[19]:
array([8.00000000e+000, 1.82804289e-322, 8.00000000e+000, 0.00000000e+000,
0.00000000e+000, 6.52741159e-038, 8.00000000e+000, 7.63251534e+169,
8.00000000e+000, 1.23967276e+224])
所以我不明白为什么会这样。我做错什么了吗?(如果是,请解释)。这是Numpy中的一个bug吗
编辑:我在多台笔记本电脑上出现过错误。所以我创建了一个小脚本,如果它在你的pc/笔记本电脑上,该怎么做呢。在脚本之前,我在我所有的机器上使用anaconda,如果这很重要的话
a = np.round(np.random.rand(10) * 3, 0)
tf = np.where(a==2, True, False)
b = np.power(a, 3, where=np.where(a==2, True, False))
b1 = np.power(a, 3, where=tf)
c = np.log10(a, where=np.where(a>2, True, False))
bits = 16
linarr = np.arange(2 ** bits) - 2 ** (bits - 1)
logarr = np.copy(linarr)
logarr = 20 * np.log10(logarr, where=np.where(linarr > 0, True, False))
我希望至少在logarr
我得到了以下方向的东西array([-32768, -32767,-32766, ... , 0, ... 90.3085, 90.3087])
,但我得到了array([1.76e-314, 1.72-314, 2.12e-312, ... , 0, ... 90.3085, 90.3087])
目前没有回答
相关问题 更多 >
编程相关推荐