np.empty_like not working with zeros array
See original GitHub issueWhen an array created using np.zeros is passed as an argument to np.empty_like, the array is initialized to 0 instead of being uninitialized!
Reproducing code example:
a = np.zeros((2, 5), dtype=np.float32)
print(a)
b = np.empty_like(a)
print(b)
Output:
[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
Numpy/Python version information:
System: Linux
Numpy Version: 1.18.1
Python Version: 3.6.9
Issue Analytics
- State:
- Created 4 years ago
- Comments:8 (8 by maintainers)
Top Results From Across the Web
Why numpy.empty_like() return an array fill with zero is unsafe?
The implementation of numpy.empty() does not write the value of zero to the addresses of memory it reserves for the array.
Read more >numpy.zeros_like — NumPy v1.24 Manual
numpy.zeros_like# ... Return an array of zeros with the same shape and type as a given array. ... Overrides the data type of...
Read more >NumPy: Create an ndarray with all elements initialized with ...
This article describes how to create a NumPy array ndarray with all elements initialized with the same value (0, 1, given value).
Read more >NumPy: empty_like() function - w3resource
The empty_like() function is used to create a new array with the same shape and type as a given array. Syntax: numpy.empty_like(prototype ...
Read more >numpy.empty_like() in Python - GeeksforGeeks
numpy.empty_like(a, dtype = None, order = 'K', subok = True) : Return a new array with the same shape and type as a...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

The result can depend on when
print()is called. For example:Output:
But this version
generates:
So I suspect there is nothing to be concerned about.
This is on macOS 10.12.6, with numpy 1.17.2.
Thanks Warren, nice catch. I will close this. This is the caching mechanism that numpy uses to avoid many small/mid-sized allocations, and thus is simply expected here currently.