Python - Fraction


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import fractions
  2.  
  3. print "separate numerator and demoninator"
  4. for n, d in [ (1,3), (2,6), (3,9) ] :
  5. f = fractions.Fraction(n,d)
  6. print "%s/%s = %s" % (n,d,f)
  7.  
  8. print "string : numerator/denominator"
  9. for s in [ '1/3', '2/6', '3/9' ] :
  10. f = fractions.Fraction(s)
  11. print "%s = %s" % (s,f)
  12.  
  13. print "floating point notation"
  14. for s in [ '0.5', '1.5', '2.0'] :
  15. f = fractions.Fraction(s)
  16. print "%s = %s" % (s,f)
  17.  
  18. print "creating fraction instance from values"
  19. for v in [ 0.1, 0.5, 1.5, 2.0] :
  20. print "%s = %s" % (v, fractions.Fraction.from_float(v))
  21.  
  22. Output :
  23. separate numerator and demoninator
  24. 1/3 = 1/3
  25. 2/6 = 1/3
  26. 3/9 = 1/3
  27. string : numerator/denominator
  28. 1/3 = 1/3
  29. 2/6 = 1/3
  30. 3/9 = 1/3
  31. floating point notation
  32. 0.5 = 1/2
  33. 1.5 = 3/2
  34. 2.0 = 2
  35. creating fraction instance from values
  36. 0.1 = 3602879701896397/36028797018963968
  37. 0.5 = 1/2
  38. 1.5 = 3/2
  39. 2.0 = 2

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.