Why does the division get rounded to an integer?(为什么除法四舍五入为整数?)
问题描述
我试图将一组从 -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.因为 0.111 小于 0.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
这篇关于为什么除法四舍五入为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么除法四舍五入为整数?
基础教程推荐
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
