By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,236 Members | 1,011 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,236 IT Pros & Developers. It's quick & easy.

Floating point operations

P: 18
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
Expand|Select|Wrap|Line Numbers
  1.       L = [1,2]
  2.     average = (sum(L))/len(L)
  3.     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

Expand|Select|Wrap|Line Numbers
  1.  a = 0.5
But what about the case above? The only way I could think of is to say

Expand|Select|Wrap|Line Numbers
  1.     L = [1,2]
  2.     average = (sum(L) * 1.0)/len(L)
  3.     print average
Thanks in advance.
I am using Python 2.5 on WinXP.
Mar 17 '08 #1
Share this Question
Share on Google+
2 Replies

P: 314
You could type cast into float like this:
Expand|Select|Wrap|Line Numbers
  1. >>> avg = (sum(L))/float(len(L))
  2. >>> avg
  3. 1.5
When a float is used in division, the result is not rounded for integer division.
Mar 17 '08 #2

P: 18
Thanks a lot for your help, jlm.
Mar 18 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.