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

ดูขีดจำกัดของเครื่องสำหรับจำนวนเต็มพร้อมอินสแตนซ์ใน Python

ในการดูขีดจำกัดของเครื่องสำหรับชนิดข้อมูลจำนวนเต็ม ใช้เมธอด numpy.iinfo() ใน NumPy พารามิเตอร์แรกคือชนิดข้อมูลจำนวนเต็มที่ต้องการข้อมูล

ขั้นตอน

ขั้นแรก ให้นำเข้าไลบรารี:

import numpy as np

min คือค่าต่ำสุดของ dtype ที่กำหนด และ max คือค่าสูงสุด

ตรวจสอบชนิด int16 พร้อมอินสแตนซ์:

a = np.iinfo(np.int16(20))
print("Minimum of int16 type...\n", a.min)
print("Maximum of int16 type...\n", a.max)

ตรวจสอบชนิด int32 พร้อมอินสแตนซ์:

b = np.iinfo(np.int32(30))
print("\nMinimum of int32 type...\n", b.min)
print("Maximum of int32 type...\n", b.max)

ตรวจสอบชนิด int64 พร้อมอินสแตนซ์:

c = np.iinfo(np.int64(50))
print("\nMinimum of int64 type...\n", c.min)
print("Maximum of int64 type...\n", c.max)

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

import numpy as np
# ดูขีดจำกัดของเครื่องสำหรับชนิดข้อมูลจำนวนเต็ม
# ใช้ numpy.iinfo() ใน Python NumPy
# พารามิเตอร์แรกคือชนิดข้อมูลจำนวนเต็มที่ต้องการข้อมูล

# ตรวจสอบชนิด int16 พร้อมอินสแตนซ์
# min คือค่าต่ำสุดของ dtype ที่กำหนด
# max คือค่าสูงสุดของ dtype ที่กำหนด
a = np.iinfo(np.int16(20))
print("Minimum of int16 type...\n", a.min)
print("Maximum of int16 type...\n", a.max)

# ตรวจสอบชนิด int32 พร้อมอินสแตนซ์
b = np.iinfo(np.int32(30))
print("\nMinimum of int32 type...\n", b.min)
print("Maximum of int32 type...\n", b.max)

# ตรวจสอบชนิด int64 พร้อมอินสแตนซ์
c = np.iinfo(np.int64(50))
print("\nMinimum of int64 type...\n", c.min)
print("Maximum of int64 type...\n", c.max)

ผลลัพธ์

Minimum of int16 type... -32768
Maximum of int16 type... 32767
Minimum of int32 type... -2147483648
Maximum of int32 type... 2147483647
Minimum of int64 type... -9223372036854775808
Maximum of int64 type... 9223372036854775807