Фанки Джаз - 1 year ago 64

Python Question

`import numpy as np`

from numpy.random import randn

N = 100000

counter = 0

for i in randn(N):

if i < 1 and i > -1:

counter = counter + 1

counter/N

The code resulted in an output of ZERO everytime.

I changed the 100000 to 100000.0 and it gave me the 68% but informed me the following:

anaconda/lib/python2.7/site-packages/ipykernel/main.py:5:

VisibleDeprecationWarning: using a non-integer number instead of an

integer will result in an error in the future"

Can you help me figure out what is happening?

Answer Source

You are performing an integer division. Integer division means, that it will round down the result of the division, like

```
>>> print(99 / 100)
0
```

You can perform a "normal" division, by converting one (or both) of the operands to a float.

```
float(counter) / float(N)
```

The other effect that you see (the VisibleDeprecationWarning) results from `N`

being an `float`

in this case. The function `randn`

takes an integer as parameter, not a float. See numpy.random.randn. An older version of numpy allowed using a float, but now it is deprecated. This means, that it will still work, but isn't good practice anymore.