Return to Snippet

Revision: 17711
at September 12, 2009 03:20 by wearetherock


Updated Code
import fractions

print "separate numerator and demoninator"
for n, d in [ (1,3), (2,6), (3,9) ] :
	f = fractions.Fraction(n,d)
	print "%s/%s = %s" % (n,d,f)

print "string : numerator/denominator"
for s in [ '1/3', '2/6', '3/9' ] :
	f = fractions.Fraction(s)
	print "%s = %s" % (s,f)

print "floating point notation"
for s in [ '0.5', '1.5', '2.0'] :
	f = fractions.Fraction(s)
	print "%s = %s" % (s,f)

print "creating fraction instance from values"
for v in [ 0.1, 0.5, 1.5, 2.0] :
	print "%s = %s" % (v, fractions.Fraction.from_float(v))

Output :
separate numerator and demoninator
1/3 = 1/3
2/6 = 1/3
3/9 = 1/3
string : numerator/denominator
1/3 = 1/3
2/6 = 1/3
3/9 = 1/3
floating point notation
0.5 = 1/2
1.5 = 3/2
2.0 = 2
creating fraction instance from values
0.1 = 3602879701896397/36028797018963968
0.5 = 1/2
1.5 = 3/2
2.0 = 2

Revision: 17710
at September 12, 2009 03:18 by wearetherock


Initial Code
import fractions

print "separate numerator and demoninator"
for n, d in [ (1,3), (2,6), (3,9) ] :
	f = fractions.Fraction(n,d)
	print "%s/%s = %s" % (n,d,f)

print "string : numerator/denominator"
for s in [ '1/3', '2/6', '3/9' ] :
	f = fractions.Fraction(s)
	print "%s = %s" % (s,f)

print "floating point notation"
for s in [ '0.5', '1.5', '2.0'] :
	f = fractions.Fraction(s)
	print "%s = %s" % (s,f)

print "creating fraction instance from values"
for v in [ 0.1, 0.5, 1.5, 2.0] :
	print "%s = %s" % (v, fractions.Fraction.from_float(v))

<pre>
Output :
separate numerator and demoninator
1/3 = 1/3
2/6 = 1/3
3/9 = 1/3
string : numerator/denominator
1/3 = 1/3
2/6 = 1/3
3/9 = 1/3
floating point notation
0.5 = 1/2
1.5 = 3/2
2.0 = 2
creating fraction instance from values
0.1 = 3602879701896397/36028797018963968
0.5 = 1/2
1.5 = 3/2
2.0 = 2
</pre>

Initial URL
http://broadcast.oreilly.com/2009/09/pymotw-fractions---rational-nu.html

Initial Description

                                

Initial Title
Python - Fraction

Initial Tags
python

Initial Language
Python