Python事业部 [英] Python division

查看:67
本文介绍了Python事业部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一组从-100到0的数字归一化到10-100的范围,并且遇到了问题,只是注意到即使根本没有任何变量,这也无法评估我期望的方式:

I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evaluate the way I would expect it to:

>>> (20-10) / (100-10)
0

浮点划分也不起作用:

>>> float((20-10) / (100-10))
0.0

如果除法的任何一侧都转换为浮点数,它将起作用:

If either side of the division is cast to a float it will work:

>>> (20-10) / float((100-10))
0.1111111111111111

第一个示例中的每一方都将int评估为int,这意味着最终答案将转换为int.由于0.111小于.5,因此将其舍入为0.在我看来,这不是透明的,但我想是这样的.

Each side in the first example is evaluating as an int which means the final answer will be cast to an int. Since 0.111 is less than .5, it rounds to 0. It is not transparent in my opinion, but I guess that's the way it is.

解释是什么?

推荐答案

您正在使用Python 2.x,其中整数除法将被截断而不是成为浮点数.

You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.

>>> 1 / 2
0

您应该将其中一个设置为float:

You should make one of them a float:

>>> float(10 - 20) / (100 - 10)
-0.1111111111111111

from __future__ import division,强制/采用Python 3.x的行为,该行为始终返回浮点数.

or from __future__ import division, which the forces / to adopt Python 3.x's behavior that always returns a float.

>>> from __future__ import division
>>> (10 - 20) / (100 - 10)
-0.1111111111111111

这篇关于Python事业部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆