2

In NumPy there are two functions, one is numpy.random.rand() and another is numpy.empty(). Both functions are giving me same output. Code:

>>> import numpy as np
>>> np.random.rand(3,2)
array([[0.54372255, 0.68730993],
       [0.97759727, 0.39876009],
       [0.47325882, 0.57949219]])

>>> np.empty([3,2])
array([[0.54372255, 0.68730993],
       [0.97759727, 0.39876009],
       [0.47325882, 0.57949219]])

Because both of them are giving the same output, both are the same or different? here I mean with same that both functions have similar implementations or they have different implementations

If both are different then which one is better or efficient?

3
  • Read their documentation to see, that those do not have anything in common. Maybe also google uninitialized memory (or wikis Uninitialized variable). Commented Jan 5, 2021 at 11:52
  • 2
    They are not the same, try using both functions in reverse order. numpy uses memory available from your previous initialization to claim memory for np.empty(), because it is a block of memory with an appropriate size. Commented Jan 5, 2021 at 11:59
  • Oh, i understand. Commented Jan 5, 2021 at 13:09

1 Answer 1

4

They are different!

Rand, based on a seed generate some numbers of a given shape.

On the other part, empty return an unitializated array, so it means that is pointing to a random memory location, accidentally this return random values, but out of control, in your example gc has released the memoty location so the same area was occupied by empty with the same shape.

So don't use empty for generate random values

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

Comments

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.