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

ดูขีดจำกัดของเครื่องสำหรับชนิดข้อมูลจุดลอยตัวใน Python

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

ขั้นตอน

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

import numpy as np

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

ตรวจสอบชนิด float16:

a = np.finfo(np.float16)
print("Minimum of float16 type...\n", a.min)
print("Maximum of float16 type...\n", a.max)

ตรวจสอบชนิด float32:

b = np.finfo(np.float32)
print("\nMinimum of float32 type...\n", b.min)
print("Maximum of float32 type...\n", b.max)

ตรวจสอบชนิด float64:

c = np.finfo(np.float64)
print("\nMinimum of float64 type...\n", c.min)
print("Maximum of float64 type...\n", c.max)

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

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

# ตรวจสอบชนิด float16
# min คือค่าต่ำสุดของ dtype ที่กำหนด
# max คือค่าสูงสุดของ dtype ที่กำหนด
a = np.finfo(np.float16)
print("Minimum of float16 type...\n", a.min)
print("Maximum of float16 type...\n", a.max)

# ตรวจสอบชนิด float32
b = np.finfo(np.float32)
print("\nMinimum of float32 type...\n", b.min)
print("Maximum of float32 type...\n", b.max)

# ตรวจสอบชนิด float64
c = np.finfo(np.float64)
print("\nMinimum of float64 type...\n", c.min)
print("Maximum of float64 type...\n", c.max)

ผลลัพธ์

Minimum of float16 type... -65500.0
Maximum of float16 type... 65500.0
Minimum of float32 type... -3.4028235e+38
Maximum of float32 type... 3.4028235e+38
Minimum of float64 type... -1.7976931348623157e+308
Maximum of float64 type... 1.7976931348623157e+308