jeudi 2 novembre 2023

how to replace every element of a zeros numpy array with a random number with uniform distribution between -1 and 1 including both -1 and 1 in python

I want to generate a numpy array with a specific shape filled with zeros. then after some operations replace every single element of the array with a random uniform distribution number between [-1, 1] including both -1 and 1.

I tried this code below but it seems as discussed Here [low, high) (includes low, but excludes high this code does not include 1 ever.

import numpy as np


np.random.seed(0)

# the shape must be one of the following.
# the_shape_of_array = (5)
# the_shape_of_array = (8, 5)
the_shape_of_array = (3, 8, 5)

my_array = np.zeros(the_shape_of_array)
# Doing some operations with the array
length_of_shape_of_my_array = len(my_array.shape)
if length_of_shape_of_my_array == 1:
    for element_index, _ in enumerate(my_array):
        my_array[element_index] = np.random.uniform(-1, 1)
elif length_of_shape_of_my_array == 2:
    for row_index, row in enumerate(my_array):
        for element_index, _ in enumerate(row):
            my_array[row_index][element_index] = np.random.uniform(-1, 1)
elif length_of_shape_of_my_array == 3:
    for block_index, block in enumerate(my_array):
        for row_index, row in enumerate(block):
            for element_index, _ in enumerate(row):
                my_array[block_index][row_index][element_index] = np.random.uniform(
                    -1, 1
                )
print(my_array)

I also tried 2 * np.random.rand() - 1 instead np.random.uniform(-1, 1) but it was the same.

what should I do?

I tried the code that I sent and I expect the code to generate random values including both -1 and 1.




Aucun commentaire:

Enregistrer un commentaire