ในการหาจำนวนบิตในส่วนเลขชี้กำลัง (exponent) ของการแสดงจุดลอยตัว สามารถใช้แอตทริบิวต์ iexp ของเมธอด numpy.finfo() ในไลบรารี NumPy พารามิเตอร์แรกคือชนิดข้อมูลจุดลอยตัวที่ต้องการข้อมูล
ขั้นตอน
ขั้นแรก ให้นำเข้าไลบรารีที่จำเป็น:
import numpy as np
ตรวจสอบชนิด float16 แอตทริบิวต์ iexp ใช้สำหรับหาจำนวนบิตในส่วนเลขชี้กำลัง min คือค่าต่ำสุดของชนิดข้อมูลที่กำหนด และ max คือค่าสูงสุด:
a = np.finfo(np.float16(45.9))
print("Number of bits in the exponent portion float16 type...\n", a.iexp)
print("Minimum of float16 type...\n", a.min)
print("Maximum of float16 type...\n", a.max)
ตรวจสอบชนิด float32 ด้วยอินสแตนซ์:
b = np.finfo(np.float32(22.3))
print("\nNumber of bits in the exponent portion float32 type...\n", b.iexp)
print("Minimum of float32 type...\n", b.min)
print("Maximum of float32 type...\n", b.max)
ตรวจสอบชนิด float64 (ค่าเริ่มต้นของ Python) ด้วยอินสแตนซ์:
c = np.finfo(np.float64(29.2))
print("\nNumber of bits in the exponent portion float64 type...\n", c.iexp)
print("Minimum of float64 type...\n", c.min)
print("Maximum of float64 type...\n", c.max)
ตัวอย่างโค้ดเต็ม
import numpy as np
# หาจำนวนบิตในส่วนเลขชี้กำลังของการแสดงจุดลอยตัว
# ใช้แอตทริบิวต์ iexp ของ numpy.finfo() ใน Python NumPy
# พารามิเตอร์แรกคือชนิดข้อมูลจุดลอยตัวที่ต้องการข้อมูล
# ตรวจสอบชนิด float16
# iexp ใช้หาจำนวนบิตในส่วนเลขชี้กำลัง
# min คือค่าต่ำสุดของ dtype ที่กำหนด
# max คือค่าสูงสุดของ dtype ที่กำหนด
a = np.finfo(np.float16(45.9))
print("Number of bits in the exponent portion float16 type...\n", a.iexp)
print("Minimum of float16 type...\n", a.min)
print("Maximum of float16 type...\n", a.max)
# ตรวจสอบชนิด float32 ด้วยอินสแตนซ์
b = np.finfo(np.float32(22.3))
print("\nNumber of bits in the exponent portion float32 type...\n", b.iexp)
print("Minimum of float32 type...\n", b.min)
print("Maximum of float32 type...\n", b.max)
# ตรวจสอบชนิด float64 ด้วยอินสแตนซ์
c = np.finfo(np.float64(29.2))
print("\nNumber of bits in the exponent portion float64 type...\n", c.iexp)
print("Minimum of float64 type...\n", c.min)
print("Maximum of float64 type...\n", c.max)
ผลลัพธ์
Number of bits in the exponent portion float16 type... 5 Minimum of float16 type... -65500.0 Maximum of float16 type... 65500.0 Number of bits in the exponent portion float32 type... 8 Minimum of float32 type... -3.4028235e+38 Maximum of float32 type... 3.4028235e+38 Number of bits in the exponent portion float64 type... 11 Minimum of float64 type... -1.7976931348623157e+308 Maximum of float64 type... 1.7976931348623157e+308