Simrandeep Bahal
Simrandeep Bahal

Reputation: 119

Getting zeros every time while using random function in Python

I am doing this as shown below. Initially I have a 2D array A = [(1,2,3) , (4,5,6)]. Now through a function func , I want to replace all the elements in both the two rows of array A by random numbers. I am trying but I am getting every element as 0 after execution of the function. Can somebody help. Remember I have to do this problem by using this function func and doing these slicing operations.

import numpy as np
import random
A=np.array([(1,2,3),(4,5,6)])
def func(B):
    B[0:3]= np.random.random((1,3))
    return(B)
                    
for ic in range(0,2):
    A[ic,:]= func(A[ic,:])

print(A)    
Output
Everytime I am getting zeros. There should be random numbers in both the rows of array A . I think the random number generator is generating zeros every time. Can somebody help ??
[[0 0 0]
 [0 0 0]]

Upvotes: 4

Views: 864

Answers (3)

RajezPrince
RajezPrince

Reputation: 34

your code with small modifications

import numpy as np
from random import random
A=np.array([(1,2,3),(4,5,6)])
def func(B):
    B[0:3]= np.random.choice((1,3))
    return(B)
                
for ic in range(0,2):
A[ic,:]= func(A[ic,:])

print(A)  

Instead of np.random.random you can use np.random.choice, it will generate random numbers

Upvotes: 1

Ianhi
Ianhi

Reputation: 3152

The way you are constructing the array A is such that it will always have integer dtype. You can check with print(A.dtype). This means that values that are between 0-1 are getting cast to zero which is a problem because np.random.rand only returns values between 0 and 1. You can fix this in a few ways:

  1. Construct using floats A=np.array([(1.,2.,3.),(4.,5.,6.)])
  2. Set dtype explicitly A=np.array([(1,2,3),(4,5,6)], dtype=np.float)
  3. cast to float type A=np.array([(1,2,3),(4,5,6)]).astype(np.float)

Upvotes: 6

Mad Physicist
Mad Physicist

Reputation: 114330

The issue is that A is an array of integers, and np.random.random generates floats that are less than one for practical purposes. Casting such a number to integer always yields zero.

You can fix in one of two ways:

  1. Make A an array of float dtype:

    a. A = np.array([[1.0, 2, 3], [4, 5, 6]])
    b. A = np.array([[1, 2, 3], [4, 5, 6]], dtype=float)
    c. etc...

  2. Generate random integers instead of floats, or at least floats that would cast to nonzero integers:

    a. B[:]= np.random.randint(256, size=B.shape)
    b. B[:]= np.random.random(B.shape) * 256 c. etc...

Upvotes: 2

Related Questions