Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Python, why does preallocation of a numpy array fail to limit its printed precision?

Here is a minimal example:

import numpy as np
np.set_printoptions(linewidth=1000, precision=3)

# First attempt fails to limit the printed precision of x
x = np.array([None])
x[0] = 1/3
print(x)

# Second attempt succeeds
x = [None]
x[0] = 1/3
x = np.array(x)
print(x)

Running this script yields

[0.3333333333333333]
[0.333]

Why does the "First attempt" above fail to limit the printed precision of x while the second attempt succeeds?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When running:

x = np.array([None])
x[0] = 1/3
print(x)

x is an object array (that contains python floats), not an array with a float dtype like your second attempt:

array([0.3333333333333333], dtype=object)

This ignores the print options.

You can reproduce this simply with:

print(np.array([1/3], dtype=object), np.array([1/3]))

Output: [0.3333333333333333] [0.333]

As a workaround, convert your array to float:

print(x.astype(np.float64))
# [0.333]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading