【问题标题】:Numpy power does not allow negative valuesNumpy power 不允许负值
【发布时间】:2018-06-12 16:29:39
【问题描述】:

我有体积数据,我想从中构建一个八度音阶:2^n : 1,2,4,8,16,32,64...等 n = 0,1,2,3,4, 5,6...

体积数据:

Biovolume (µm³)   
0.238873
1.05251
2.82718

我的代码是:

import pandas as pd
import numpy as np

#data file
data = pd.read_csv("data.csv")

#define and sort biovolume
Biovolume = data['Biovolume'].as_matrix()
Biovolume = np.sort(Biovolume)

#octave scale:
min_scale = np.floor(np.log2(np.min(Biovolume))).astype('int')
max_scale = np.ceil(np.log2(np.max(Biovolume))).astype('int')

体积数据的刻度最小值为 -3,最大值为 2。 下一步是为数据实际构建八度音阶:

octave_scale = np.power(2, range(min_scale, max_scale+1))

但是,我收到此错误: ValueError: 整数的负整数幂是不允许的。

我猜这意味着不可能进行 2^-3、2^-2 和 2^-1。 为什么是这样?有解决办法吗?

【问题讨论】:

标签: python numpy negative-number raise


【解决方案1】:

请参阅 this answer 了解为什么 np.power 不处理负整数。

一种解决方案是使用np.float_power,它专门用于处理负能量。来自docs

目的是该函数将为负幂返回一个可用的结果,而对于正幂则很少溢出。

示例:

>>> np.power(5,-2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Integers to negative integer powers are not allowed.
>>> np.float_power(5, -2)
0.040000000000000001

【讨论】:

  • 非常感谢!我确实有一些积极的价值观,它也对他们有用。
猜你喜欢
  • 2020-10-08
  • 1970-01-01
  • 2018-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 2013-11-25
  • 2011-11-29
相关资源
最近更新 更多