سؤال

As a project, I am creating a Rational Class from scratch that can take two fractions as input and store the simplified fraction. However, when I attempt to input two fractions, it appears to use integer division implicitly, so I can't store/manipulate the fraction at all. Am I approaching the problem incorrectly? Where is the mistake?

Example: Rational(3/2,9/2) returns (1,4) rather than (1/3).

def gcd(numerator,denominator):
    if numerator < 0:
        absNum = -numerator
    elif denominator < 0:
        absDen = -denominator
    else:
        absNum = numerator
        absDen = denominator    

    while absNum != absDen:
        if absNum > absDen:
            absNum = absNum - absDen
        elif absDen >= absNum:
            absDen = absDen - absNum
    return(absNum)


class Rational:
    def __init__(self,numerator=0,denominator=1):
        self.numerator = numerator
        self.denominator = denominator
        if denominator == 0:
            raise ZeroDivisionError("Error: cannot store number with 0 in denominator.")
        elif denominator < 0:
            if numerator < 0:
                self.denominator = -denominator
                self.numerator = -numerator
            else:
                self.numerator = numerator
                self.denominator = -denominator 
        if numerator != 0:
            com = gcd(numerator,denominator)
            numerator = numerator/com
            denominator = denominator/com
            self.numerator = numerator
            self.denominator = denominator


Rational(5/3,8/3)

Returns (1,2) instead of, (5,8) as it should. EDIT: The second half: I want to be able to input Rational(Rational(5/3),Rational(8/3)) with (5,8) the result. This seems slightly different from the above.

هل كانت مفيدة؟

المحلول

from __future__ import division

will fix the division problem.

Side note - if you want your rationals to be stored precisely, you should make sure the numerator and denominator are both being stored as ints. If I'm reading it correctly, your gcd function won't work with floats.

To solve this problem you might want to do something like:

def __init__(self, num, den):
    num1, den1 = float(num).as_integer_ratio()
    den2, num2 = float(den).as_integer_ratio()
    self.numerator = num1 * num2
    self.denominator = den1 * den2
    ...

نصائح أخرى

It's not the storage of the variable, but the expression instantiating your class. If you use two integers it will implicitly use integer division. You should use fractions or use the float() function.

my_rational = Rational(3.0/2,9.0/2)

my_other_rational = Rational(float(3)/2,float(9)/2)

Edit: In Python 3.x it's no longer the case. See: http://www.python.org/dev/peps/pep-0238/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top