title: Index Error: index 3 is out of bounds for axis 1 with size 3
body: <p>I am running the following code where the function <code>weighted_values</code> returns a sequence of random values with probabilities as specified. I am using this function from this answer <a href="https://stackoverflow.com/questions/11373192/generating-discrete-random-variables-with-specified-weights-using-scipy-or-numpy">Generating discrete random variables with weights</a></p>
  
  <p>The following is my code:</p>
  
  <pre><code>def weighted_values(values, probabilities, size):
      bins = np.add.accumulate(probabilities)
      return np.array(values[np.digitize(random_sample(size), bins)])
  
  def weak_softmax(a):
      b=np.exp(a)
      return b/(1+sum(b))
  
  
   elements=np.array([1,2,3])
   prob=np.array([0.2,0.5,0.3])
  
  
   system_index=0;
   T=10;M=2;
  
  for t in np.arange(T):
  
       prob=weak_softmax(np.random.uniform(0,1,M+1));
  
       system_index=weighted_values(np.arange(M+1),prob,1)[0]
  
  print(system_index)
  </code></pre>
  
  <p>However when I run this code, sometimes I get this error that</p>
  
  <pre><code> Traceback (most recent call last):
   File "gradient_checking.py", line 75, in &lt;module&gt;
      system_index=weighted_values(np.arange(M+1),prob,1)[0]
   File "gradient_checking.py", line 57, in weighted_values
      return np.array(values[np.digitize(random_sample(size), bins)])
   IndexError: index 3 is out of bounds for axis 1 with size 3
  </code></pre>
  
  <p>Can anyone suggest what I am doing wrong and how to modify it?</p>