-1

I have written the following code but it fails with a ValueError.

from numpy import *
from pylab import *

t = arange(-10, 10, 20/(1001-1))
x = 1./sqrt(2*pi)*exp(power(-(t*t), 2))

Specifically, the error message I'm receiving is:

ValueError: a <= 0
    x = 1./sqrt(2*pi)*exp(power(-(t*t), 2))
  File "mtrand.pyx", line 3214, in mtrand.RandomState.power (numpy\random\mtrand\mtrand.c:24592)
Traceback (most recent call last):
  File "D:\WinPython-64bit-3.4.4.3Qt5\notebooks\untitled1.py", line 6, in <module>

Any idea what the issue might be here?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Addung
  • 1
  • 3
    Stop using `import *`, especially `from pylab import *`. – user2357112 Aug 15 '16 at 17:29
  • 4
    Welcome to Stack Overflow, please give this a read: http://stackoverflow.com/help/how-to-ask – n1c9 Aug 15 '16 at 17:30
  • 2
    I upvoted @user2357112's comment, but that isn't a strong enough agreement in this case. Really, truly, emphatically: don't use `import *`! It is the source of the problem in this case. Both `numpy` and `pylab` define a function called `power`, but they are completely different. Because you imported `pylab` after `numpy` using `import *`, the `pylab` version is the one you end up with. What is `pylab.power`? From the docstring: *"power(a, size=None) Draws samples in [0, 1] from a power distribution with positive exponent a - 1."* – Warren Weckesser Aug 15 '16 at 18:04
  • @WarrenWeckesser unless you're aware of a dup, why not add it as an answer? – Dimitris Fasarakis Hilliard Aug 15 '16 at 18:14
  • While not exactly a dup, perhaps http://stackoverflow.com/questions/2386714/why-is-import-bad is "morally" a dup, and there are probably other questions where the fundamental problem is a namespace clash resulting from `import *`, but those are hard to search for, so sure, I'll add an answer. – Warren Weckesser Aug 15 '16 at 20:08

1 Answers1

2

Both numpy and pylab define a function called power, but they are completely different. Because you imported pylab after numpy using import *, the pylab version is the one you end up with. What is pylab.power? From the docstring:

power(a, size=None)

Draws samples in [0, 1] from a power distribution with positive exponent a - 1.

The moral of the story: don't use import *. In this case, it is common to use import numpy as np:

import numpy as np

t = np.arange(-10, 10, 20/(1001-1))
x = 1./np.sqrt(2*np.pi)*np.exp(np.power(-(t*t), 2))

Further reading:

Community
  • 1
  • 1
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214