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

  Kiến thức lập trình

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?

When running:

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

x is an object dataframe (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]

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT