Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tìm kiểu dữ liệu tối thiểu của giá trị scalar trong Python

Phương thức numpy.min_scalar_type() xác định kiểu dữ liệu NumPy nhỏ nhất có thể chứa một giá trị scalar cho trước. Với scalar, trả về dtype có kích thước nhỏ nhất và loại scalar phù hợp. Với mảng non-scalar, trả về dtype của mảng gốc. Các giá trị float không được hạ cấp thành int, complex không hạ cấp thành float.

Các bước thực hiện

Nhập NumPy:

import numpy as np

Kiểm tra các giá trị khác nhau:

print("Sử dụng min_scalar_type() trong NumPy\n")
print("Kết quả...", np.min_scalar_type(55))      # int dương nhỏ
print("Kết quả...", np.min_scalar_type(38.9))    # float
print("Kết quả...", np.min_scalar_type(-78))     # int âm
print("Kết quả...", np.min_scalar_type(479))     # int lớn hơn uint8
print("Kết quả...", np.min_scalar_type(2e100))   # float rất lớn
print("Kết quả...", np.min_scalar_type(-45.8))   # float âm
print("Kết quả...", np.min_scalar_type(6.5e100)) # float rất lớn

Ví dụ hoàn chỉnh

import numpy as np

print("Sử dụng min_scalar_type() trong NumPy\n")
print("Kết quả...", np.min_scalar_type(55))
print("Kết quả...", np.min_scalar_type(38.9))
print("Kết quả...", np.min_scalar_type(-78))
print("Kết quả...", np.min_scalar_type(479))
print("Kết quả...", np.min_scalar_type(2e100))
print("Kết quả...", np.min_scalar_type(-45.8))
print("Kết quả...", np.min_scalar_type(6.5e100))

Kết quả đầu ra

Sử dụng min_scalar_type() trong NumPy
Kết quả... uint8
Kết quả... float16
Kết quả... int8
Kết quả... uint16
Kết quả... float64
Kết quả... float16
Kết quả... float64