Rahultripathy
Rahultripathy

Reputation: 33

how to get fraction as it is ( without getting itssimplest fraction )? i vainly tried using this:

x=7
y=14
from fractions import Fraction
print(Fraction(7/14))

I got answer 1/2 but I needed 7/14. is there any way to write as it is without using string?

Upvotes: 3

Views: 1167

Answers (1)

Ciaran Liedeman
Ciaran Liedeman

Reputation: 779

Most fraction libraries will simplify the numerator and denominator as soon as they are created as a performance optimization. If you are working with large unsimplified fractions there is a chance that they will overflow. So before each operation the fractions will have to be simplified anyway.

If you want to keep the original numerator and denominator intact you should create your own wrapper class like so:

class MyFraction:
    def __init__(self, numerator=1, denominator=1):
        self.numerator = numerator
        self.denominator = denominator

    def get_fraction(self):
        from fractions import Fraction
        return Fraction(numerator=self.numerator, denominator=self.denominator)

    def __repr__(self):
        return '{}/{}'.format(self.numerator, self.denominator)

f = MyFraction(numerator=7, denominator=14)
print(f)  # prints 7/14
print(f.get_fraction())  # prints 1/2

Note: You should be invoking fraction using the Fraction(numerator=0, denominator=1) constructor.

Is your case what is happening is:

Fraction(7/14) => Fraction(0.5) => 1/2

Upvotes: 3

Related Questions