jpcgandre
jpcgandre

Reputation: 1505

Rounding of variables

I have the following code:

x=4200/820

It should return x=5.12 but it gives x=5. How can I change this. Thanks

EDIT: If instead I had this code:

x=(z-min(z_levels))/(max(z_levels)-min(z_levels))

Where z, min(z_levels) and max(z_levels) are values that change in a for loop taken from a list. How can I make x a float? Do I need to change the code like this:?

x=float(z-min(z_levels))/float(max(z_levels)-min(z_levels))

Upvotes: 0

Views: 1692

Answers (4)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250991

In python2.x integer division always results in truncated output, but if one of the operand is changed to float then the output is float too.

In [40]: 4200/820
Out[40]: 5

In [41]: 4200/820.0
Out[41]: 5.121951219512195

In [42]: 4200/float(820)
Out[42]: 5.121951219512195

This has been changed in python 3.x, in py3x / results in True division(non-truncating) while // is used for truncated output.

In [43]: from __future__ import division #import py3x's division in py2x

In [44]: 4200/820
Out[44]: 5.121951219512195

Upvotes: 2

Krzysztof Bujniewicz
Krzysztof Bujniewicz

Reputation: 2417

You should cast at least one variable/value to float, ie. x=float(4200)/float(820) or use a decimal point to indicate that value is a float (x=4200/820.)

Or you can use from __future__ import division, then regular int division will return floats.

In [1]: from __future__ import division

In [2]: 4200/820
Out[2]: 5.121951219512195

To achieve python 2x style integer division (where result is a rounded integer) after this import, you should use // operator:

In [22]: 4200//820
Out[22]: 5

Upvotes: 2

Moj
Moj

Reputation: 6361

one of them should be float:

In [152]: 4200/820.
Out[152]: 5.121951219512195

Upvotes: 1

Nolen Royalty
Nolen Royalty

Reputation: 18633

Use a decimal to make python use floats

>>> x=4200/820.
>>> x
5.121951219512195

If you then want to round x to 5.12, you can use the round function:

>>> round(x, 2)
5.12

Upvotes: 4

Related Questions