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

หาชนิดข้อมูลขั้นต่ำของค่าสเกลาร์ใน Python ด้วย numpy.min_scalar_type()

เมธอด numpy.min_scalar_type() ใช้หาชนิดข้อมูล (data type) ขั้นต่ำที่สามารถเก็บค่าสเกลาร์ที่กำหนดได้ สำหรับค่าสเกลาร์ จะคืนชนิดข้อมูลที่มีขนาดเล็กที่สุดและชนิดสเกลาร์ที่เล็กที่สุดซึ่งสามารถเก็บค่านั้นได้ สำหรับอาร์เรย์ที่ไม่ใช่สเกลาร์ จะคืน dtype ของเวกเตอร์เดิม ค่าจุดทศนิยมจะไม่ถูกลดระดับเป็นจำนวนเต็ม และค่าฤทธิ์จะไม่ถูกลดระดับเป็นจำนวนจริง

ขั้นตอนการใช้งาน

import numpy as np

ตัวอย่างการหาชนิดข้อมูลขั้นต่ำของค่าต่างๆ

print("Using the min_scalar_type() method in Numpy\n")
print("Result...", np.min_scalar_type(55))
print("Result...", np.min_scalar_type(38.9))
print("Result...", np.min_scalar_type(-78))
print("Result...", np.min_scalar_type(479))
print("Result...", np.min_scalar_type(2e100))
print("Result...", np.min_scalar_type(-45.8))
print("Result...", np.min_scalar_type(6.5e100))

โค้ดตัวอย่างสมบูรณ์

import numpy as np

# For scalar, returns the data type with the smallest size and smallest scalar kind which can hold its value.
# For non-scalar array, returns the vector's dtype unmodified.
# Floating point values are not demoted to integers, and complex values are not demoted to floats.

print("Using the min_scalar_type() method in Numpy\n")
print("Result...", np.min_scalar_type(55))
print("Result...", np.min_scalar_type(38.9))
print("Result...", np.min_scalar_type(-78))
print("Result...", np.min_scalar_type(479))
print("Result...", np.min_scalar_type(2e100))
print("Result...", np.min_scalar_type(-45.8))
print("Result...", np.min_scalar_type(6.5e100))

ผลลัพธ์ที่คาดหวัง

Using the min_scalar_type() method in Numpy
Result... uint8
Result... float16
Result... int8
Result... uint16
Result... float64
Result... float16
Result... float64