Hướng dẫn convert number to fraction python - đổi số thành phân số python

Để mở rộng khi Martijn Pieters trả lời tuyệt vời với một tùy chọn bổ sung do sự thiếu chính xác vốn có với những chiếc phao phức tạp hơn. Ví dụ:

>>> f = 0.8857097
>>> f.as_integer_ratio()
(1994440937439217, 2251799813685248)          # mathematically wrong
>>> Fraction(f)
Fraction(1994440937439217, 2251799813685248)  # same result but in a class
>>> Fraction(f).limit_denominator()
Fraction(871913, 984423)                      # still imprecise

Kết quả toán học mong muốn là

>>> Fraction(str(f))
Fraction(8857097, 10000000)
1 có thể đạt được bằng cách đúc vào một chuỗi và sau đó thao túng nó.

Phản hồi chỉnh sửa

Tôi tìm thấy một cách đơn giản hơn nhiều để giải quyết vấn đề chính xác.

>>> Fraction(str(f))
Fraction(8857097, 10000000)

Đúc như một chuỗi cũng cho phép các phiên bản thập phân chính xác

>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)

Phản hồi ban đầu

def float_to_ratio(flt):
    if int(flt) == flt:        # to prevent 3.0 -> 30/10
        return int(flt), 1
    flt_str = str(flt)
    flt_split = flt_str.split('.')
    numerator = int(''.join(flt_split))
    denominator = 10 ** len(flt_split[1])
    return numerator, denominator

Bây giờ chúng ta hãy kiểm tra nó:

>>> float_to_ratio(f)
(8857097, 10000000)      # mathematically correct

Tôi sẽ lưu ý rằng loại độ chính xác phân số này không được tối ưu hóa và thường sẽ không cần thiết, nhưng để hoàn thiện, nó ở đây. Chức năng này không đơn giản hóa phân số, nhưng bạn có thể thực hiện xử lý bổ sung để giảm nó:

>>> n = 0.5
>>> float_to_ratio(n)
(5, 10)
>>> Fraction(*float_to_ratio(n))
Fraction(1, 2)

Mã nguồn: lib/phân số.py Lib/fractions.py


Mô -đun

>>> Fraction(str(f))
Fraction(8857097, 10000000)
2 cung cấp hỗ trợ cho số học số hợp lý.

Một thể hiện phân số có thể được xây dựng từ một cặp số nguyên, từ một số hợp lý khác hoặc từ một chuỗi.

classFractions.Fraction (Numerator = 0, mẫu số = 1) ¶ classFractions.Fraction (other_fraction) classFractions.Fraction (float) classFractions.Fraction (thập phân) classfractions.fraction (chuỗi)fractions.Fraction(numerator=0, denominator=1)classfractions.Fraction(other_fraction) class fractions.Fraction(float) classfractions.Fraction(decimal) class fractions.Fraction(string)

Phiên bản đầu tiên yêu cầu tử số và mẫu số là các phiên bản là

>>> Fraction(str(f))
Fraction(8857097, 10000000)
3 và trả về một thể hiện
>>> Fraction(str(f))
Fraction(8857097, 10000000)
4 mới với giá trị
>>> Fraction(str(f))
Fraction(8857097, 10000000)
5. Nếu mẫu số là
>>> Fraction(str(f))
Fraction(8857097, 10000000)
6, nó sẽ tăng
>>> Fraction(str(f))
Fraction(8857097, 10000000)
7. Phiên bản thứ hai yêu cầu các trường hợp khác là một thể hiện của
>>> Fraction(str(f))
Fraction(8857097, 10000000)
3 và trả về một thể hiện
>>> Fraction(str(f))
Fraction(8857097, 10000000)
4 với cùng một giá trị. Hai phiên bản tiếp theo chấp nhận một ví dụ
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
0 hoặc
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
1 và trả về một thể hiện
>>> Fraction(str(f))
Fraction(8857097, 10000000)
4 với chính xác cùng một giá trị. Lưu ý rằng do các vấn đề thông thường với điểm nổi nhị phân (xem Số học điểm nổi: Các vấn đề và giới hạn), đối số với
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
3 không chính xác bằng 11/10, và do đó
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
3 không trả lại
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
5 như người ta có thể mong đợi. (Nhưng xem tài liệu cho phương thức
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
6 bên dưới.) Phiên bản cuối cùng của hàm tạo mong đợi một trường hợp chuỗi hoặc unicode. Mẫu thông thường cho trường hợp này là:Floating Point Arithmetic: Issues and Limitations), the argument to
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
3 is not exactly equal to 11/10, and so
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
3 does not return
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
5 as one might expect. (But see the documentation for the
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
6 method below.) The last version of the constructor expects a string or unicode instance. The usual form for this instance is:

[sign] numerator ['/' denominator]

trong đó

>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
7 tùy chọn có thể là ‘+hoặc hoặc‘-và và
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
8 và
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
9 (nếu có) là các chuỗi của các chữ số thập phân (có thể sử dụng các chữ số để phân định các chữ số như với các chữ viết tích hợp trong mã). Ngoài ra, bất kỳ chuỗi nào đại diện cho một giá trị hữu hạn và được chấp nhận bởi hàm tạo
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
0 cũng được chấp nhận bởi hàm tạo
>>> Fraction(str(f))
Fraction(8857097, 10000000)
4. Trong cả hai hình thức, chuỗi đầu vào cũng có thể có khoảng trắng dẫn đầu và/hoặc dấu vết. Dưới đây là một số ví dụ:

>>> from fractions import Fraction
>>> Fraction(16, -10)
Fraction(-8, 5)
>>> Fraction(123)
Fraction(123, 1)
>>> Fraction()
Fraction(0, 1)
>>> Fraction('3/7')
Fraction(3, 7)
>>> Fraction(' -3/7 ')
Fraction(-3, 7)
>>> Fraction('1.414213 \t\n')
Fraction(1414213, 1000000)
>>> Fraction('-.125')
Fraction(-1, 8)
>>> Fraction('7e-6')
Fraction(7, 1000000)
>>> Fraction(2.25)
Fraction(9, 4)
>>> Fraction(1.1)
Fraction(2476979795053773, 2251799813685248)
>>> from decimal import Decimal
>>> Fraction(Decimal('1.1'))
Fraction(11, 10)

Lớp

>>> Fraction(str(f))
Fraction(8857097, 10000000)
4 kế thừa từ lớp cơ sở trừu tượng
>>> Fraction(str(f))
Fraction(8857097, 10000000)
3 và thực hiện tất cả các phương pháp và hoạt động từ lớp đó. Các trường hợp
>>> Fraction(str(f))
Fraction(8857097, 10000000)
4 có thể băm, và nên được coi là bất biến. Ngoài ra,
>>> Fraction(str(f))
Fraction(8857097, 10000000)
4 có các thuộc tính và phương pháp sau:

Đã thay đổi trong phiên bản 3.9: Hàm

def float_to_ratio(flt):
    if int(flt) == flt:        # to prevent 3.0 -> 30/10
        return int(flt), 1
    flt_str = str(flt)
    flt_split = flt_str.split('.')
    numerator = int(''.join(flt_split))
    denominator = 10 ** len(flt_split[1])
    return numerator, denominator
6 hiện được sử dụng để bình thường hóa tử số và mẫu số.
def float_to_ratio(flt):
    if int(flt) == flt:        # to prevent 3.0 -> 30/10
        return int(flt), 1
    flt_str = str(flt)
    flt_split = flt_str.split('.')
    numerator = int(''.join(flt_split))
    denominator = 10 ** len(flt_split[1])
    return numerator, denominator
6 Luôn trả về loại
def float_to_ratio(flt):
    if int(flt) == flt:        # to prevent 3.0 -> 30/10
        return int(flt), 1
    flt_str = str(flt)
    flt_split = flt_str.split('.')
    numerator = int(''.join(flt_split))
    denominator = 10 ** len(flt_split[1])
    return numerator, denominator
8. Trước đây, loại GCD phụ thuộc vào tử số và mẫu số.The
def float_to_ratio(flt):
    if int(flt) == flt:        # to prevent 3.0 -> 30/10
        return int(flt), 1
    flt_str = str(flt)
    flt_split = flt_str.split('.')
    numerator = int(''.join(flt_split))
    denominator = 10 ** len(flt_split[1])
    return numerator, denominator
6 function is now used to normalize the numerator and denominator.
def float_to_ratio(flt):
    if int(flt) == flt:        # to prevent 3.0 -> 30/10
        return int(flt), 1
    flt_str = str(flt)
    flt_split = flt_str.split('.')
    numerator = int(''.join(flt_split))
    denominator = 10 ** len(flt_split[1])
    return numerator, denominator
6 always return a
def float_to_ratio(flt):
    if int(flt) == flt:        # to prevent 3.0 -> 30/10
        return int(flt), 1
    flt_str = str(flt)
    flt_split = flt_str.split('.')
    numerator = int(''.join(flt_split))
    denominator = 10 ** len(flt_split[1])
    return numerator, denominator
8 type. Previously, the GCD type depended on numerator and denominator.

Đã thay đổi trong phiên bản 3.11: Dấu gạch dưới hiện được cho phép khi tạo một thể hiện

>>> Fraction(str(f))
Fraction(8857097, 10000000)
4 từ một chuỗi, tuân theo các quy tắc PEP 515.Underscores are now permitted when creating a
>>> Fraction(str(f))
Fraction(8857097, 10000000)
4 instance from a string, following PEP 515 rules.

Đã thay đổi trong phiên bản 3.11:

>>> Fraction(str(f))
Fraction(8857097, 10000000)
4 thực hiện
>>> float_to_ratio(f)
(8857097, 10000000)      # mathematically correct
1 ngay bây giờ để thỏa mãn kiểm tra cá thể
>>> float_to_ratio(f)
(8857097, 10000000)      # mathematically correct
2.
>>> Fraction(str(f))
Fraction(8857097, 10000000)
4 implements
>>> float_to_ratio(f)
(8857097, 10000000)      # mathematically correct
1 now to satisfy
>>> float_to_ratio(f)
(8857097, 10000000)      # mathematically correct
2 instance checks.

tử số¶

Tử số của phân số trong thời hạn thấp nhất.

mẫu số

Mẫu số của phân số trong thời hạn thấp nhất.

as_integer_ratio () ¶()

Trả về một tuple của hai số nguyên, có tỷ lệ bằng phân số và với mẫu số dương.

Mới trong phiên bản 3.8.

classmethodfrom_float (flt) ¶ from_float(flt)

Hàm tạo thay thế chỉ chấp nhận các trường hợp

>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
0 hoặc
>>> float_to_ratio(f)
(8857097, 10000000)      # mathematically correct
4. Hãy coi chừng
>>> float_to_ratio(f)
(8857097, 10000000)      # mathematically correct
5 không giống với giá trị
>>> float_to_ratio(f)
(8857097, 10000000)      # mathematically correct
6.

Ghi chú

Từ Python 3.2 trở đi, bạn cũng có thể xây dựng một thể hiện

>>> Fraction(str(f))
Fraction(8857097, 10000000)
4 trực tiếp từ
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
0.

classmethodfrom_decimal (tháng 12) ¶from_decimal(dec)

Hàm tạo thay thế chỉ chấp nhận các trường hợp

>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)
1 hoặc
>>> float_to_ratio(f)
(8857097, 10000000)      # mathematically correct
4.

giới hạn_denominator (max_denominator = 1000000) ¶(max_denominator=1000000)

Tìm và trả về

>>> Fraction(str(f))
Fraction(8857097, 10000000)
4 gần nhất cho
>>> n = 0.5
>>> float_to_ratio(n)
(5, 10)
>>> Fraction(*float_to_ratio(n))
Fraction(1, 2)
2 có mẫu số ở hầu hết MAX_DENOMINATOR. Phương pháp này rất hữu ích để tìm các xấp xỉ hợp lý cho một số điểm nổi nhất định:

>>> from fractions import Fraction
>>> Fraction('3.1415926535897932').limit_denominator(1000)
Fraction(355, 113)

hoặc để phục hồi một số hợp lý mà LỚN đại diện cho một chiếc phao:

>>> from math import pi, cos
>>> Fraction(cos(pi/3))
Fraction(4503599627370497, 9007199254740992)
>>> Fraction(cos(pi/3)).limit_denominator()
Fraction(1, 2)
>>> Fraction(1.1).limit_denominator()
Fraction(11, 10)

__sàn nhà__()¶()

Trả về

def float_to_ratio(flt):
    if int(flt) == flt:        # to prevent 3.0 -> 30/10
        return int(flt), 1
    flt_str = str(flt)
    flt_split = flt_str.split('.')
    numerator = int(''.join(flt_split))
    denominator = 10 ** len(flt_split[1])
    return numerator, denominator
8 lớn nhất
>>> n = 0.5
>>> float_to_ratio(n)
(5, 10)
>>> Fraction(*float_to_ratio(n))
Fraction(1, 2)
4. Phương pháp này cũng có thể được truy cập thông qua hàm
>>> n = 0.5
>>> float_to_ratio(n)
(5, 10)
>>> Fraction(*float_to_ratio(n))
Fraction(1, 2)
5:

>>> Fraction(str(f))
Fraction(8857097, 10000000)
0

__ceil __ ()()

Trả về ít nhất

def float_to_ratio(flt):
    if int(flt) == flt:        # to prevent 3.0 -> 30/10
        return int(flt), 1
    flt_str = str(flt)
    flt_split = flt_str.split('.')
    numerator = int(''.join(flt_split))
    denominator = 10 ** len(flt_split[1])
    return numerator, denominator
8
>>> n = 0.5
>>> float_to_ratio(n)
(5, 10)
>>> Fraction(*float_to_ratio(n))
Fraction(1, 2)
7. Phương pháp này cũng có thể được truy cập thông qua hàm
>>> n = 0.5
>>> float_to_ratio(n)
(5, 10)
>>> Fraction(*float_to_ratio(n))
Fraction(1, 2)
8.

__round __ () __Round __ (ndigits)()__round__(ndigits)

Phiên bản đầu tiên trả lại

def float_to_ratio(flt):
    if int(flt) == flt:        # to prevent 3.0 -> 30/10
        return int(flt), 1
    flt_str = str(flt)
    flt_split = flt_str.split('.')
    numerator = int(''.join(flt_split))
    denominator = 10 ** len(flt_split[1])
    return numerator, denominator
8 gần nhất đến
>>> n = 0.5
>>> float_to_ratio(n)
(5, 10)
>>> Fraction(*float_to_ratio(n))
Fraction(1, 2)
2, làm tròn một nửa vào chẵn. Phiên bản thứ hai làm tròn
>>> n = 0.5
>>> float_to_ratio(n)
(5, 10)
>>> Fraction(*float_to_ratio(n))
Fraction(1, 2)
2 đến bội số gần nhất của
[sign] numerator ['/' denominator]
2 (về mặt logic, nếu
[sign] numerator ['/' denominator]
3 là âm), một lần nữa làm tròn một nửa về phía chẵn. Phương pháp này cũng có thể được truy cập thông qua hàm
[sign] numerator ['/' denominator]
4.

Xem thêm

Mô -đun
[sign] numerator ['/' denominator]
5

Các lớp cơ sở trừu tượng tạo nên tháp số.