Question

I have from a dataset I load in 2 values.

x1=5.904e-16

and

x1=1.048576e-14

granted these are tiny numbers, but all I want to do is average them.

avg = 1/2*(x1+x2)

but this gives avg = 0

Arr!

Was it helpful?

Solution

I assume you're using Python 2.

When both arguments are integers, Python 2 uses integer division, which means that the result will also be an integer. For example:

print 1/2
# 0
print 5/2
# 2

To overcome this, either use the float equivalent (0.5), or change one of the arguments to the division (either 1 or 2, doesn't matter) to a float, so that it will return a float as well.

print 1.0/2
# 0.5
print 1/2.0
# 0.5
print 1.0/2.0
# 0.5

You could also, as nneonneo mentioned, put the sum straight into the division, like so:

(x1+x2)/2.0

This will also give the desired result.

OTHER TIPS

avg = 0.5*(x1+x2)

worked because 1/2 apparently in python is not equal to 0.5 but no it sees 1/2 as one over two and no values past a decimal on either so it assumes you do not care about wanting that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top