运行时警告使用Numpy的电源

时间:2014-10-20 20:56:43

标签: python-3.x numpy

我正在使用numpy的电源功能,我正在收到警告信息。这是代码:

import numpy as np


def f(x, n):
    factor = n / (1. + n)
    exponent = 1. + (1. / n)
    f1_x = factor * np.power(0.5, exponent) - np.power(0.5 - x, exponent)
    f2_x = factor * np.power(0.5, exponent) - np.power(x - 0.5, exponent)
    return np.where((0 <= x) & (x <= 0.5), f1_x, f2_x)

fv = np.vectorize(f, otypes='f')
x = np.linspace(0., 1., 20)
print(fv(x, 0.23))

这是警告信息:

  

E:\ ProgramasPython3 \ LibroCientifico \ partesvectorizada.py:8:   运行警告:电源遇到无效值f2_x = factor *   np.power(0.5,指数) - np.power(x - 0.5,指数)   E:\ ProgramasPython3 \ LibroCientifico \ partesvectorizada.py:7:   运行时警告:电源中遇到无效值f1_x = factor *   np.power(0.5,exponent) - np.power(0.5 - x,指数)[-0.0199636   -0.00895462 -0.0023446 0.00136486 0.003271 0.00414007     0.00447386 0.00457215 0.00459036 0.00459162 0.00459162 0.00459036     0.00457215 0.00447386 0.00414007 0.003271 0.00136486 -0.0023446 -0.00895462 -0.0199636]

我不知道什么是无效值。并且我不知道如何指定numpy函数f2_x仅对于> 0.5和&lt; = 1.0之间的值有效。 感谢

2 个答案:

答案 0 :(得分:2)

发生这种情况的原因是因为你试图采用负数的非整数幂。显然,如果您没有明确地将值转换为复杂的,那么这在早期版本的Python / Numpy中不起作用。所以你必须做类似

的事情

np.power(complex(0.5 - x), exponent) <击> .real

编辑:由于你的价值观真的很复杂(不是一些真实的数字+一些微小的想象部分),我想你会想要使用复杂的(但是<= )稍后会变得有点困难,或者你想要以其他方式捕捉基数为负的情况。

答案 1 :(得分:0)

好的,非常感谢大家,这里的解决方案是使用分段函数来反对numpy,并使用np.complex128提到 @Saullo

   import numpy as np


    def f(x, n):
        factor = n / (1. + n)
        exponent = (n + 1.) / n
        f1_x = lambda x: factor * \
            np.power(2., -exponent) - np.power((1. - 2. * x) / 2., exponent)
        f2_x = lambda x: factor * \
            np.power(2., -exponent) - np.power(-(1. - 2. * x) / 2., exponent)
        conditions = [(0. <= x) & (x <= 0.5), (0.5 < x) & (x <= 1.)]
        functions = [f1_x, f2_x]
        result = np.piecewise(x, conditions, functions)
        return np.real(result)

    x = np.linspace(0., 1., 20)
    x = x.astype(np.complex128)
    print(f(x, 0.23))

问题是当电源的基数为负时,np.power不能正常工作并且您获得警告消息。我希望这对每个人都有用。