簡體   English   中英

如何簡化我課堂上的分數?

[英]How to simplify fractions in my class?

這是我的Fraction類代碼:

class Fraction:
    """Class for performing fraction arithmetic.
    Each Fraction has two attributes: a numerator, n and a deconominator, d.
    Both must be integer and the deonominator cannot be zero.
    """
    def __init__(self,n,d):
        """Performs error checking and standardises to ensure denominator is positive"""
        if type(n)!=int or type(d)!=int:
            raise TypeError("n and d must be integers")
        if d==0:
            raise ValueError("d must be positive")
        elif d<0:
            self.n = -n
            self.d = -d
        else:
            self.n = n
            self.d = d

    def __str__(self):
        """Gives string representation of Fraction (so we can use print)"""
        return(str(self.n) + "/" + str(self.d))

    def __add__(self, otherFrac):
        """Produces new Fraction for the sum of two Fractions"""
        newN = self.n*otherFrac.d + self.d*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __sub__(self, otherFrac):
        """Produces new Fraction for the difference between two Fractions"""
        newN = self.n*otherFrac.d - self.d*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __mul__(self, otherFrac):
        """Produces new Fraction for the product of two Fractions"""
        newN = self.n*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __truediv__(self, otherFrac):
        """Produces new Fraction for the quotient of two Fractions"""
        newN = self.n*otherFrac.d
        newD = self.d*otherFrac.n
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __eq__(self,otherFrac):
        return(self.n * otherFrac.d) == (self.d * otherFrac.n)

為了使該類更有用,如何簡化分數?

例如:我想將30/15更改為5/3? 看起來像:
(30/2)/(18/2)---> 15/9 ----->(15/3)/(9/3)-----> 5/3

而且我不使用import fraction

您想找到分子和分母的最大公約數 ,然后除以兩者。 gcd函數在Python的標准庫中,但是您可能想自己實現。 找到它的一種著名(且易於實現)的算法稱為Euclid算法

您可以通過將兩個數字相減以獲得第三個數字(差),然后丟棄三個數字中的最大數字並重復此減法/舍棄過程直到其中一個數字為零,來實現Euclid算法。

順便說一句,減少的30/15是2/1。

舉個例子(30/15)

30-15 = 15

現在您有3個數字(30、15、15)。 丟棄最大的並重復。

15-15 = 0

現在您有3個較小的數字(15、15、0)。

15-0 = 15

因為那並沒有改變數字的集合,所以可以得出結論,15是最大公約數。 (如果將30和15除以15,則得到2和1,這是減數的分子和分母。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM