3

what is the best way to create a NumPy array of a given size with values randomly and uniformly spread between -1 and 1?

I tried 2*np.random.rand(size)-1

4
  • 1
    It should work. Commented Apr 20, 2019 at 1:09
  • 1
    Your way seems fine to me. Commented Apr 20, 2019 at 1:10
  • 1
    What's the problem with what you tried? Commented Apr 20, 2019 at 1:19
  • Thank you. You are right, it works. I was looking for a numpy function that would give me such an array without the x2 trick. Commented Apr 20, 2019 at 10:56

4 Answers 4

7

I'm not sure. Try:

s = np.random.uniform(-1, 1, size)

reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html

Sign up to request clarification or add additional context in comments.

Comments

1

In your solution the np.random.rand(size) returns random floats in the half-open interval [0.0, 1.0)

this means 2 * np.random.rand(size) - 1 returns numbers in the half open interval [0, 2) - 1 := [-1, 1), i.e. range including -1 but not 1.

If this is what you wish to do then it is okay.

But, if you wish to generate numbers in the open interval (-1, 1), i.e. between -1 and 1 and hence not including either -1 or 1, may I suggest the following -

from numpy.random import default_rng
rg = default_rng(2)

size = (5,5)

rand_arr = rg.random(size)
rand_signs = rg.choice([-1,1], size)

rand_arr = rand_arr * rand_signs

print(rand_arr)

I have used the new suggested Generator per numpy, see link https://numpy.org/devdocs/reference/random/index.html#quick-start

Comments

0

I can use numpy.arange:

import numpy as np

print(np.arange(start=-1.0, stop=1.0, step=0.2, dtype=np.float))

The step parameter defines the size and the uniformity in the distribution of the elements.

Comments

0

100% working Code:

a = np.random.uniform(-1,1)
print(a)

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
your not answering the question of size. Also, the correct with np.random.uniform was already posted in 2019

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.