ภาพรวม
ใช้ numpy.result_type() คืน dtype ที่ได้จากการ apply NumPy type promotion rules กับ arguments การ promote types ใน NumPy คล้าย C++ แต่มีความแตกต่างเล็กน้อย ถ้ามีทั้ง scalars และ arrays array type จะมี precedence และค่าจริงของ scalar ถูกนำไปพิจารณา
พารามิเตอร์
operands: operands ของ operation ที่ต้องการ result type
ขั้นตอนการทำงาน
1. นำเข้า NumPy
import numpy as np
2. ทดสอบ result_type() กรณีต่างๆ
print("Using the result_type() method in Numpy\n")
print("Result...", np.result_type(2, np.arange(4, dtype='i1')))
print("Result...", np.result_type(5, 8))
print("Result...", np.result_type('i4', 'c8'))
print("Result...", np.result_type(3.8, 8))
print("Result...", np.result_type(5, 20.7))
print("Result...", np.result_type(-8, 20.7))
print("Result...", np.result_type(10.0, -4))
ตัวอย่างโค้ดเต็ม
import numpy as np
print("Using the result_type() method in Numpy\n")
print("Result...", np.result_type(2, np.arange(4, dtype='i1')))
print("Result...", np.result_type(5, 8))
print("Result...", np.result_type('i4', 'c8'))
print("Result...", np.result_type(3.8, 8))
print("Result...", np.result_type(5, 20.7))
print("Result...", np.result_type(-8, 20.7))
print("Result...", np.result_type(10.0, -4))
ผลลัพธ์
Using the result_type() method in Numpy Result... int8 Result... int64 Result... complex128 Result... float64 Result... float64 Result... float64 Result... float64
คำอธิบาย:
- Scalar 2 + int8 array → int8 (array type precedence, scalar value fits in int8)
- 5, 8 (Python ints) → int64 (default integer)
- int32 + complex64 → complex128
- float + int → float64
- int + float → float64
- negative int + float → float64
- float + negative int → float64