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

ฟังก์ชัน as_integer_ratio() ใน Python สำหรับหาส่วนของทศนิยม

ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่คืนค่าตัวเลข 2 ตัว ซึ่งอัตราส่วนของพวกเขาเท่ากับค่าทศนิยมที่กำหนด เรามีเมธอดชื่อ as_integer_ratio() ที่ช่วยให้บรรลุเป้าหมายนี้ได้

ตัวอย่าง

Input: 1.5
Output: 3 / 2

Input: 5.3
Output: 5967269506265907 / 1125899906842624

ตัวอย่างโค้ดที่ 1

# initializing the float value
float_value = 1.5

# getting integers tuple using as_integer_ratio()
integers = float_value.as_integer_ratio()

# printing the integers
print(f'{integers[0]} / {integers[1]}')

ผลลัพธ์

3 / 2

ตัวอย่างโค้ดที่ 2

float_value = 5.3
integers = float_value.as_integer_ratio()
print(f'{integers[0]} / {integers[1]}')

ผลลัพธ์

5967269506265907 / 1125899906842624

คำอธิบาย

เมธอด as_integer_ratio() คืนค่าเป็น tuple ของจำนวนเต็ม 2 ตัว (numerator, denominator) ที่อัตราส่วนเท่ากับค่า float เดิม สำหรับ 1.5 ได้ 3/2 ซึ่งถูกต้องและลดรูปแล้ว ส่วน 5.3 ให้ตัวเลขใหญ่มากเพราะการแทนค่าทศนิยมใน binary ไม่แม่นยำ (floating point representation)

สรุป

as_integer_ratio() เหมาะสำหรับการแปลง float ให้เป็นเศษส่วนที่แม่นยำ หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็น