2

I have encountered a strange behavior of python numpy; if I consider the following code:

import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
    x=np.linspace(-1.0, 0.0, 5)
    L=1.65
    y=x**L
    plt.plot(x,y)
    plt.show()

The vector y=[nan,nan,nan,nan,0.], instead if the code is the following:

import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
    x=np.linspace(0.0, 1.0, 5)
    L=1.65
    y=x**L
    plt.plot(x,y)
    plt.show()

results in y=[0.,0.10153155,0.31864016,0.62208694,1.] which is correct.

So the question is what is the problem? Is it a bug or I'm doing something wrong? I'm using Python 2.7.11 | Anaconda 4.0.0.

wnnmaw
  • 5,444
  • 3
  • 38
  • 63
LucaG
  • 341
  • 3
  • 11

1 Answers1

3

You cannot raise negative real numbers to fractional powers

In python 2.7 try doing (-1)**1.65 and see the python error

As @Blckknght mention in the comments, given (-1)**1.65, python 3 will automatically return a complex number, instead of raising an exception

To achieve what you want you need to cast the array x to complex numbers

import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
    x=np.linspace(-1.0, 0.0, 5).astype(np.complex64)
    L=1.65
    y=x**L
    plt.plot(x,y)
    plt.show()

Check ValueError: negative number cannot be raised to a fractional power and How to raise arrays with negative values to fractional power in Python?

Community
  • 1
  • 1
Makis Tsantekidis
  • 2,698
  • 23
  • 38
  • 3
    It's worth noting that Python 3 will automatically return a `complex` value when you do `(-1)**1.65`, rather than raising an exception. That's new behavior though, and `numpy` still behaves the same way. – Blckknght May 31 '16 at 14:54
  • Thanks, i was quite sure I was doing something wrong indeed!!! Of course I have to use complex number, thanks again... – LucaG May 31 '16 at 15:11