Q:

Runtime Warning Using power with Numpy

I'm using power function from numpy and i'm obtaining a warning message. This is the code:
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))

And this is the warning message:

E:\ProgramasPython3\LibroCientifico\partesvectorizada.py:8:
  RuntimeWarning: invalid value encountered in power   f2_x = factor *
  np.power(0.5, exponent) - np.power(x - 0.5, exponent)
  E:\ProgramasPython3\LibroCientifico\partesvectorizada.py:7:
  RuntimeWarning: invalid value encountered in power   f1_x = factor *
  np.power(0.5, exponent) - np.power(0.5 - x, exponent) [-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 ]

I don't know what is the invalid value. And I don't know how to specify that with where numpy function f2_x is only valid for values between >0.5 and <= 1.0.
Thanks

A:

The reason this happens is because you are trying to take a non-integer power of a negative number. Apparently this doesn't work in earlier versions of Python/Numpy if you don't explicitly cast the value to be complex. So you will have to do something like 
np.power(complex(0.5 - x), exponent).real
EDIT : Since your values will be truly complex (not some real number + some tiny imag part), I think you would want to either use the complex (but then the <=) later on gets kind of difficult, or you would want to catch the case where the base is negative in some other way.

