-1

I have the following program

def F_inf(a,b):
    x1=a.numerator/a.denominator
    x2=b.numerator/b.denominator

        if x1<x2:
            print "a<b"
    elif x1>x2:
        print "a>b"
    else: print "a=b" 

a=Fraction(10,4)
b=Fraction(10,4)

F_inf(a, b)

When I execute it,x1 receive just the integer value of the fraction, for exemple if I have to compute 2/4 x1 is equal to 0 not 0.5. What should I do ? Thanks

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Younès Raoui
  • 211
  • 5
  • 10

1 Answers1

1

It sounds like you're using Python2. The best solution would be to switch to Python 3 (not just because of the division but because "Python 2.x is legacy, Python 3.x is the present and future of the language").

Other than that you have a couple of choices.

from __future__ import division
# include ^ as the first line in your file to use float division by default

or

a = 1
b = 2
c = a / (1.0*b) # multiplying by 1.0 forces the right side of the division to be a float
#c == 0.5 here
Holloway
  • 6,412
  • 1
  • 26
  • 33
  • Your advice is to switch to Python3 just because Python2.x returns integer on division of two integers? – Moinuddin Quadri Jan 11 '18 at 21:06
  • 2
    @MoinuddinQuadri, No my advice is to switch to Python 3 because Python 2 is an old version that is only recommended for supporting existing legacy software. OP appears to still be learning the language so there is no reason to learn 2. This is the easiest time to switch. The division bit is a bonus. – Holloway Jan 11 '18 at 21:09
  • Thanks it works with the multiplication by 1.0 – Younès Raoui Jan 11 '18 at 21:34
  • @StefanPochmann, you're right. I had the precedence of `/`/`*` the wrong way round. Brackets added. – Holloway Jan 12 '18 at 10:27
  • I'd say you can't get their precedence "the wrong way round", since they have the same :-) – Stefan Pochmann Jan 12 '18 at 11:20
  • True. Maybe 1.0*a/b would have been better. – Holloway Jan 12 '18 at 11:32