jimistephen
Posts: 6
Joined: Sat Mar 01, 2014 4:42 am

Fractions

Sat Mar 22, 2014 2:48 pm

Hello,
I'm new to programming and have been writing a program that ask for mesurments and then figures out the area of shapes. The only problem is I can't figure out how to use fractions. The only one I need to use are really 1/2, 1/3 and 1/4. I read though /usr/lib/python2.7/fractions/.py but it was really confusing.

Can some one tell me how to use fractions and just as importantly why it's done like that (they why is so I can understand how to change it and keep using it).

User avatar
joan
Posts: 14960
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Fractions

Sat Mar 22, 2014 2:58 pm

Do you actually need fractions? For most real world problems it's simpler to use floating point.

E.g. why not just

a = 23.4
b = a/2
c = a/4
d = a/8

etc.

jimistephen
Posts: 6
Joined: Sat Mar 01, 2014 4:42 am

Re: Fractions

Sat Mar 22, 2014 3:43 pm

Well, no I guess I don't need the fractions. The one I was having trouble with is a pentagon which A=1/4math.sqrt(5(5+2marth.sqrt(5)a2 I had a working equation but it was wrong.

edit: I got it working, thanks.

User avatar
jojopi
Posts: 3274
Joined: Tue Oct 11, 2011 8:38 pm

Re: Fractions

Sun Mar 23, 2014 3:03 am

In Python 2 if you divide two integers you get an integer result; the fraction part is rounded down. If you want a floating point answer, at least one of the numbers should be a float:

Code: Select all

>>> 100 / 7
14
>>> 100.0 / 7
14.285714285714286
In Python 3 this is not necessary.

(When you actually want the truncated quotient and remainder, use // and %, which work in both versions, even for non-integers.)

Return to “Python”