บทนำ
เมธอด numpy.can_cast() ส่งคืน True หากสเกลาร์และชนิดข้อมูลสามารถแปลงได้ตามกฎการแปลง (casting rule) พารามิเตอร์แรกคือสเกลาร์หรือชนิดข้อมูลหรืออาร์เรย์ที่จะแปลงจาก พารามิเตอร์ที่สองคือชนิดข้อมูลที่จะแปลงไป
ขั้นตอน
ขั้นแรก ให้นำเข้าไลบรารีที่จำเป็น:
import numpy as np
ตรวจสอบว่าสเกลาร์และชนิดข้อมูลสามารถแปลงได้ตามกฎการแปลง:
print("ตรวจสอบด้วยเมธอด can_cast() ใน NumPy\n")
print("ผลลัพธ์...", np.can_cast(20, 'i1'))
print("ผลลัพธ์...", np.can_cast(280, 'i1'))
print("ผลลัพธ์...", np.can_cast(80, 'u1'))
print("ผลลัพธ์...", np.can_cast(300.7, np.float32))
print("ผลลัพธ์...", np.can_cast(120.6, np.float64))
print("ผลลัพธ์...", np.can_cast(7.2e100, np.float32))
print("ผลลัพธ์...", np.can_cast(6.5e100, np.float64))
ตัวอย่างโค้ดสมบูรณ์
import numpy as np
# numpy.can_cast() ส่งคืน True หากสเกลาร์และชนิดข้อมูลสามารถแปลงได้ตามกฎการแปลง
# พารามิเตอร์แรกคือสเกลาร์หรือชนิดข้อมูลหรืออาร์เรย์ที่จะแปลงจาก
# พารามิเตอร์ที่สองคือชนิดข้อมูลที่จะแปลงไป
print("ตรวจสอบด้วยเมธอด can_cast() ใน NumPy\n")
print("ผลลัพธ์...", np.can_cast(20, 'i1'))
print("ผลลัพธ์...", np.can_cast(280, 'i1'))
print("ผลลัพธ์...", np.can_cast(80, 'u1'))
print("ผลลัพธ์...", np.can_cast(300.7, np.float32))
print("ผลลัพธ์...", np.can_cast(120.6, np.float64))
print("ผลลัพธ์...", np.can_cast(7.2e100, np.float32))
print("ผลลัพธ์...", np.can_cast(6.5e100, np.float64))
ผลลัพธ์
ตรวจสอบด้วยเมธอด can_cast() ใน NumPy ผลลัพธ์... True ผลลัพธ์... False ผลลัพธ์... True ผลลัพธ์... True ผลลัพธ์... True ผลลัพธ์... False ผลลัพธ์... True