Rounding of variables

最后都变了- 提交于 2019-12-12 00:26:35

问题


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))

回答1:


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



回答2:


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



回答3:


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



回答4:


one of them should be float:

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


来源:https://stackoverflow.com/questions/16268300/rounding-of-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!