Floating point operations

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • talonx
    New Member
    • Mar 2008
    • 18

    Floating point operations

    Hello,
    I have just started learning python, so please bear with me if my question sounds very basic. (Or please point me to a relevant forum in such a case)

    Let's say I have the code
    Code:
      	L = [1,2]
    	average = (sum(L))/len(L)
    	print average
    The result is rounded off to 1, instead of 1.5 because of integer division.
    So my question is, how do I explicitly declare that I want a variable to be of floating point type? If its a preassigned value, then I can say

    Code:
     a = 0.5
    But what about the case above? The only way I could think of is to say

    Code:
    	L = [1,2]
    	average = (sum(L) * 1.0)/len(L)
    	print average
    Thanks in advance.
    I am using Python 2.5 on WinXP.
  • jlm699
    Contributor
    • Jul 2007
    • 314

    #2
    You could type cast into float like this:
    [code=python]
    >>> avg = (sum(L))/float(len(L))
    >>> avg
    1.5[/code]
    When a float is used in division, the result is not rounded for integer division.

    Comment

    • talonx
      New Member
      • Mar 2008
      • 18

      #3
      Thanks a lot for your help, jlm.

      Comment

      Working...