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

โปรแกรม Python แปลงทศนิยม float เป็นเลขฐานสอง (Binary)

กำหนดค่าทศนิยม float และจำนวนตำแหน่งทศนิยม งานของเราคือแปลงเป็นรูปแบบฐานสอง (Binary)

ขั้นตอน: แยกส่วนจำนวนเต็มและส่วนทศนิยม แปลงแต่ละส่วนเป็นฐานสอง แล้วรวมกัน

ตัวอย่างแนวคิด

ค่าทศนิยม: 22.625
แปลงส่วนจำนวนเต็ม 22 เป็น binary: 10110
แปลงส่วนทศนิยม 0.625 เป็น binary: 0.101
รวมกัน: 10110.101

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

def float_binary_convert(my_number, places=3):
    my_whole, my_dec = str(my_number).split(".")
    my_whole = int(my_whole)
    my_dec = int(my_dec)
    
    res = bin(my_whole).lstrip("0b") + "."
    
    for x in range(places):
        my_whole, my_dec = str((my_decimal_converter(my_dec)) * 2).split(".")
        my_dec = int(my_dec)
        res += my_whole
    
    return res

def my_decimal_converter(num):
    while num > 1:
        num /= 10
    return num

# Driver Code
n = input("Enter floating point value: \n")
p = int(input("Enter the number of decimal places of the result: \n"))
print(float_binary_convert(n, places=p))

ผลลัพธ์

Enter floating point value: 2.34
Enter the number of decimal places of the result: 3
10.010

หมายเหตุ: โค้ดต้นฉบับมีบั๊กที่คูณ 8 แทนที่จะคูณ 2 (คัดลอกจากโค้ด octal) โค้ดด้านบนแก้ไขแล้ว

วิธีการแปลงส่วนทศนิยมเป็น Binary (แนวคิด)

  1. คูณส่วนทศนิยมด้วย 2
  2. นำส่วนจำนวนเต็มของผลคูณ (0 หรือ 1) เป็นตัวเลข binary ตำแหน่งถัดไป
  3. นำส่วนทศนิยมของผลคูณมาคูณ 2 อีกครั้ง
  4. ทำซ้ำจนส่วนทศนิยมเป็น 0 หรือครบจำนวนตำแหน่งที่ต้องการ

ตัวอย่าง 0.625: 0.625 × 2 = 1.25 → 1 0.25 × 2 = 0.5 → 0 0.5 × 2 = 1.0 → 1 ผลลัพธ์: 0.101