Convert int to float

G

Guido van Brakel

Hello

I have this now:
def gem(a):
g = sum(a) / len(a)
return g

print gem([1,2,3,4])
print gem([1,10,100,1000])
print gem([1,-2,3,-4,5])


It now gives a int, but i would like to see floats. How can integrate
that into the function?

Regards,
 
S

sturlamolden

It now gives a int, but i would like to see floats. How can integrate
that into the function?

You get an int because you are doing integer division. Cast one int to
float.

def gem(a):
g = sum(a) / float(len(a))
return g
 
D

Dan Bishop

Hello

I have this now:
def gem(a):
g = sum(a) / len(a)
return g
print gem([1,2,3,4])
print gem([1,10,100,1000])
print gem([1,-2,3,-4,5])

It now gives a int, but i would like to see floats. How can integrate
that into the function?

If you add "from __future__ import division" at the top of the file,
division will work properly.
 
L

Lie

Hello

I have this now:
def gem(a):
    g = sum(a) / len(a)
    return g
print gem([1,2,3,4])
print gem([1,10,100,1000])
print gem([1,-2,3,-4,5])

It now gives a int, but i would like to see floats. How can integrate
that into the function?

Regards,

Python 2's division operator's default behavior is to do integer
division whenever all of its operands are integers/long and do float
division if any of them are float/decimal, in Python 3, this is going
to be changed so that division would always be float division and
while integer division would have its own operator "//".

You can change the default behavior of Python 2 by importing division
behavior from __future__ module (from __future__ import division), or
you could convert one of the operands to float ("float(a) / b" or "a /
float(b)").
 
B

Bryan Olson

sturlamolden said:
You get an int because you are doing integer division. Cast one int to
float.

def gem(a):
g = sum(a) / float(len(a))
return g

An alternative is to multiply by 1.0.

def gem(a):
g = 1.0 * sum(a) / len(a)
return g

The gem function is well-defined on sequences of complex numbers,
in which case the float() method will raise a TypeError, while
the 1.0* method will return the complex result. It may not be
what van Brakel wants here, but it's an alternative to keep in mind.

And I find it easier to type.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top