[英]I can not convert the currency conversion, using Forex, to the integer for removing the decimal division, in Python
[英]Can I keep decimal precision while using integer division in Python?
当我除2/3时我得到0.66666666,当我做2 // 3时我得到0。
有没有办法在保持小数点的同时计算整数除法?
编辑:看起来我可能很困惑你,我的坏。 所以我的教授告诉我,由于标准除法(2/3)只返回0.666666666666到203位数,所以当我想进行小数点后需要超过203位数的计算时它没有用。 我想知道是否有办法做2 // 3(将返回0)但不知何故仍然得到.6666到底
对于某些有限的小数,您可以使用Python的float .as_integer_ratio()
方法:
>>> 0.5.as_integer_ratio()
(1, 2)
对于2/3,这在十进制中不能完全表示,这开始给出不太理想的结果:
>>> (2/3).as_integer_ratio()
(6004799503160661, 9007199254740992) # approximation of 2/3
对于有理数的任意精度,在Python库中使用分数 :
>>> import fractions
>>> fractions.Fraction('2/3')
Fraction(2, 3)
>>> Frac=fractions.Fraction
>>> Frac('2/3') + Frac('1/3') + Frac('1/10')
Fraction(11, 10)
>>> Frac('2/3') + Frac('1/6') + Frac('1/10')
Fraction(14, 15)
然后,如果您想要更精确地表示十进制,请使用Decimal库将整数分子和分母转换为任意精度十进制:
>>> f=Frac('2/3') + Frac('1/6') + Frac('1/10')
>>> f
Fraction(14, 15)
>>> f.numerator
14
>>> f.denominator
15
>>> import decimal
>>> decimal.Decimal(f.numerator) / decimal.Decimal(f.denominator)
Decimal('0.9333333333333333333333333333')
您还可以在分割之前将一个整数强制转换为浮点数。
In [1]: float(2)/3
Out[1]: 0.6666666666666666
这将阻止整数截断并以float
给出结果。
也许看看decimal.Decimal()
:
>>> import decimal
>>> x = decimal.Decimal(2/3)
>>> x
Decimal('0.66666666666666662965923251249478198587894439697265625')
//
是一个分区,它会给你结果的整数层。 无论你使用2//3
还是float(2)//3
。 使用//
时无法保持精确度。
在我的环境中(python2.7.6) 2//3
返回0
并且float(2)//3
返回0.0
,两者都不能保持精度。
类似的问题可能对您有所帮助。
这不是您问题的直接答案,但它可以帮助您完成任务。
我发布了两个链接,它解释了有关实现的非常详细信息:
以下是我们需要注意的事项:
>>> 2/3
0
>>> 2/3.0
0.6666666666666666
>>> 2//3
0
>>> -2//3
-1
>>>
当前的除法运算符(/)对于数值参数有一个模糊的含义:如果参数是int或long,它返回除法的数学结果的底限,但如果参数是浮点数或复数,则返回除法结果的合理近似值。 这使得表达式期望浮点或复杂结果在不期望整数但可能作为输入时容易出错。
我们建议通过为不同的操作引入不同的运算符来解决这个问题:x / y返回分区的数学结果的合理近似值(“真正的除法”),x // y返回分层(“底层分割”)。 我们称之为x / y“经典分裂”的当前混合含义。 - Classic Division仍将是Python 2.x系列中的默认值。 真正的除法将成为Python 3.0的标准。
- The // operator will be available to request floor division
unambiguously.
- The future division statement, spelled "from __future__ import
division", will change the / operator to mean true division
throughout the module.
- A command line option will enable run-time warnings for classic
division applied to int or long arguments; another command line
option will make true division the default.
- The standard library will use the future division statement and
the // operator when appropriate, so as to completely avoid
classic division.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.