Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หาชนิดข้อมูลขั้นต่ำ (minimal data type) ของ array-like ใน Python


ภาพรวม

ใช้ numpy.min_scalar_type() หา minimal data type ที่สามารถเก็บค่าได้ สำหรับ scalar: dtype ขนาดเล็กที่สุดและ kind เล็กที่สุดที่จุค่าได้ สำหรับ non-scalar array: คืน dtype เดิม ไม่ demote float→int หรือ complex→float

พารามิเตอร์

  • value: ค่าที่ต้องการหา minimal data type

ขั้นตอนการทำงาน

1. นำเข้า NumPy

import numpy as np

2. ทดสอบ min_scalar_type() กรณีต่างๆ

print("Using the min_scalar() method in Numpy\n")
print("Result...", np.min_scalar_type(np.arange(4, dtype='f8')))
print("Result...", np.min_scalar_type(np.arange(38.9, dtype='f8')))
print("Result...", np.min_scalar_type(np.array(6.5e100, np.float64)))
print("Result...", np.min_scalar_type(np.array(280, 'i1')))
print("Result...", np.min_scalar_type(np.array(80, 'u1')))
print("Result...", np.min_scalar_type(np.array(300.7, np.float32)))
print("Result...", np.min_scalar_type(np.array(120.6, np.float64)))
print("Result...", np.min_scalar_type(np.array(7.2e100, np.float32)))
print("Result...", np.min_scalar_type(np.array(6.5e100, np.float64)))

ตัวอย่างโค้ดเต็ม

import numpy as np
print("Using the min_scalar() method in Numpy\n")
print("Result...", np.min_scalar_type(np.arange(4, dtype='f8')))
print("Result...", np.min_scalar_type(np.arange(38.9, dtype='f8')))
print("Result...", np.min_scalar_type(np.array(6.5e100, np.float64)))
print("Result...", np.min_scalar_type(np.array(280, 'i1')))
print("Result...", np.min_scalar_type(np.array(80, 'u1')))
print("Result...", np.min_scalar_type(np.array(300.7, np.float32)))
print("Result...", np.min_scalar_type(np.array(120.6, np.float64)))
print("Result...", np.min_scalar_type(np.array(7.2e100, np.float32)))
print("Result...", np.min_scalar_type(np.array(6.5e100, np.float64)))

ผลลัพธ์

Using the min_scalar() method in Numpy
Result... float64
Result... float64
Result... float64
Result... uint8
Result... uint8
Result... float16
Result... float16
Result... float16
Result... float64

คำอธิบาย:

  • Array float64 → คืน float64 (non-scalar array คืน dtype เดิม)
  • Scalar 280 ใน int8 (max 127) → overflow ต้องใช้ uint8 (max 255)
  • Scalar 80 ใน uint8 → uint8 พอดี
  • Scalar 300.7, 120.6 → float16 พอ (float16 max ~65500)
  • Scalar 7.2e100, 6.5e100 → ต้องใช้ float64 (float32 max ~3.4e38, float16 max ~65500)