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

ฟังก์ชัน ldexp() ใน Python

math.ldexp(x, i) คืนค่า x * (2 ** i) เป็น float

ตัวอย่าง

import math

print(math.ldexp(1, 4))    # 16.0
print(math.ldexp(5, -4))   # 0.3125
print(math.ldexp(-3, -1))  # -1.5

Error Handling

ถ้า argument ไม่ใช่ตัวเลข จะเกิด TypeError:

TypeError: Expected an int as second argument to ldexp.

สรุป

ใช้คำนวณ x * 2^i ได้เร็วและแม่นยำสำหรับ float