/ Published in: Python
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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
URL: http://broadcast.oreilly.com/2009/09/pymotw-fractions---rational-nu.html