在Python中使用除法运算符时如何获得十进制值?
-
02-07-2019 - |
题
例如,标准分割符号'/'舍入为零:
>>> 4 / 100
0
但是,我希望它返回0.04。我该用什么?
解决方案
有三种选择:
>>> 4 / float(100)
0.04
>>> 4 / 100.0
0.04
与C,C ++,Java等相同的行为或
>>> from __future__ import division
>>> 4 / 100
0.04
您还可以通过将参数 -Qnew
传递给Python解释器来激活此行为:
$ python -Qnew
>>> 4 / 100
0.04
第二个选项将是Python 3.0中的默认选项。如果要使用旧的整数除法,则必须使用 //
运算符。
修改:添加了关于 -Qnew
的部分,感谢Τ ΖΩΤΖΙΟΥ!
其他提示
其他答案建议如何获得浮点值。虽然这将接近你想要的,但它并不准确:
>>> 0.4/100.
0.0040000000000000001
如果您确实需要十进制值,请执行以下操作:
>>> import decimal
>>> decimal.Decimal('4') / decimal.Decimal('100')
Decimal("0.04")
这将为您提供一个正确知道 base 10 中的4/100为“0.04”的对象。浮点数实际上是基数2,即二进制,而不是十进制。
使一个或两个术语成为浮点数,如下所示:
4.0/100.0
或者,打开Python 3.0中默认的功能,'true division',即可完成您想要的功能。在模块或脚本的顶部,执行:
from __future__ import division
您可能还想查看Python的小数包。这将提供很好的小数结果。
>>> decimal.Decimal('4')/100
Decimal("0.04")
您需要告诉Python使用浮点值,而不是整数。您只需在输入中使用小数点即可完成此操作:
>>> 4/100.0
0.040000000000000001
尝试4.0 / 100
一条简单的路线4 / 100.0
或
4.0 / 100
这里我们有两种可能的情况,如下所示
from __future__ import division
print(4/100)
print(4//100)
您还可以尝试添加“.0”在数字的末尾。
4.0 / 100.0
你不能通过将一个整数除以另一个整数来得到一个十进制值,你总是得到一个整数(结果被截断为整数)。您至少需要一个值为十进制数。
使用回调功能在代码中添加以下函数。
# Starting of the function
def divide(number_one, number_two, decimal_place = 4):
quotient = number_one/number_two
remainder = number_one % number_two
if remainder != 0:
quotient_str = str(quotient)
for loop in range(0, decimal_place):
if loop == 0:
quotient_str += "."
surplus_quotient = (remainder * 10) / number_two
quotient_str += str(surplus_quotient)
remainder = (remainder * 10) % number_two
if remainder == 0:
break
return float(quotient_str)
else:
return quotient
#Ending of the function
# Calling back the above function
# Structure : divide(<divident>, <divisor>, <decimal place(optional)>)
divide(1, 7, 10) # Output : 0.1428571428
# OR
divide(1, 7) # Output : 0.1428
该功能基于“欧几里德分割算法”工作。如果您不想在项目中导入任何外部头文件,则此功能非常有用。
Syntex:除([divident],[divisor],[decimal place(optional))
代码:除(1,7,10)
或除(1,7)
以下评论任何疑问。
从未来的图书馆导入部门,如下所示:
from__future__ import division