Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting zeros every time while using random function in Python

Tags:

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]]
like image 727
Simrandeep Bahal Avatar asked Dec 30 '22 19:12

Simrandeep Bahal


2 Answers

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)
like image 147
Ianhi Avatar answered Jan 06 '23 02:01

Ianhi


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...

like image 20
Mad Physicist Avatar answered Jan 06 '23 01:01

Mad Physicist