0
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?

ayhan
  • 70,170
  • 20
  • 182
  • 203
  • 1
    Can you format the code? – Harrison Aug 31 '16 at 19:21
  • 2
    That's because of [integer division](http://stackoverflow.com/questions/2958684/python-division). When you use a float, it works properly but that's not an appropriate input for randn. So either use Python 3's division (check the linked answer for importing that) or change the last line to `counter/float(N)`. – ayhan Aug 31 '16 at 19:23
  • just a friendly suggestion, you could replace line n°7 with `counter += 1` – Daniel Kravetz Malabud Aug 31 '16 at 19:24
  • You're not returning anything.Your indenting is strange (everything after the first line is indented one time too many), which may be causing a problem. – Vivian Aug 31 '16 at 19:25
  • About *VisibleDeprecationWarning* - it shows up because the function *numpy.random.randn* does not like to receive a float parameter. – turdus-merula Aug 31 '16 at 19:29

2 Answers2

2

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.

Jakube
  • 3,353
  • 3
  • 23
  • 40
1

First of all, I'd recommend you indent your code properly so users can run it directly to diagnose your bug. Anyway, given your snippet properly formatted:

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

print(counter, N, counter / N)

Problem happens when you do counter/N using python 2.x, if that's the case you need to cast to float explicitely float(counter)/float(N). If you just used python 3.x, that float cast would be done automatically, so you wouldn't need to do it explicitely

BPL
  • 9,632
  • 9
  • 59
  • 117