在Python 2.7中,repra float返回最接近17位数的最接近的十进制数; 这足够精确,可以唯一地标识每个可能的IEEE浮点值.str一个float类似的工作,除了它将结果限制为12位数; 对于大多数用途,这是一个更合理的结果,并使您免受二进制和十进制表示之间的细微差别.
Python 2演示:http://ideone.com/OKJtxv
print str(1.4*1.5)
2.1
print repr(1.4*1.5)
2.0999999999999996
Run Code Online (Sandbox Code Playgroud)
在Python 3.2中它出现str并repr返回相同的东西.
Python 3演示:http://ideone.com/oAKRsb
print(str(1.4*1.5))
2.0999999999999996
print(repr(1.4*1.5))
2.0999999999999996
Run Code Online (Sandbox Code Playgroud)
是否存在描述变更的PEP或负责人的其他声明?
我的目标是简单地将诸如"1.2"的字符串转换为科学记数法而不增加额外的精度.问题是我总是在输出结束时得到多余的0.
>>> input = "1.2"
>>> print '{:e}'.format(float(input))
1.200000e+00
Run Code Online (Sandbox Code Playgroud)
我正在试图找出如何获得公正1.2e+00.我意识到我可以在我的格式语句中指定精度,但我不想不必要地截断更长的字符串.我只是想压制训练0.
我尝试过使用Decimal.normalize(),它适用于所有情况,除了e <2.
>>> print Decimal("1.2000e+4").normalize()
1.2E+4
>>> print Decimal("1.2000e+1").normalize()
12
Run Code Online (Sandbox Code Playgroud)
所以这更好,除了我不想要12,我想要1.2e + 1.:P
任何建议将不胜感激!
编辑: 为了澄清,输入值已经适当地舍入到预定长度,现在是未知的.我试图避免重新计算适当的格式精度.
基本上,我可以输入值"1.23"和"1234.56",它应该是"1.23e + 0"和"1.23456e + 3".
我可能只需要检查输入字符串的长度并使用它来手动指定精度,但我想检查并确保我没有遗漏可以阻止指数格式任意添加0的东西.
我有一些数字 0.0000002345E^-60。我想按原样打印浮点值。有什么方法可以做到?print %f 将其截断为 6 位数字。%n.nf 也给出了固定数字。没有截断的打印方式是什么。
我正在寻找一种有效的方法来用python确定两个浮点数的最大公约数。该例程应具有以下布局
gcd(a, b, rtol=1e-05, atol=1e-08)
"""
Returns the greatest common divisor of a and b
Parameters
----------
a,b : float
two floats for gcd
rtol, atol : float, optional
relative and absolute tolerance
Returns
-------
gcd : float
Greatest common divisor such that for x in [a,b]:
np.mod(x,gcd) < rtol*x + atol
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
"""
Run Code Online (Sandbox Code Playgroud)
示例:有理数和无理数的gcd
本gcd(1., np.pi, rtol=0, atol=1e-5)应返回(大约)1e-5,如
In [1]: np.mod(np.pi,1e-5)
Out[1]: 2.6535897928590063e-06
In [2]: np.mod(1.,1e-5)
Out[2]: 9.9999999999181978e-06
Run Code Online (Sandbox Code Playgroud)
我宁愿使用库实现而不是自己编写它。该fractions.gcd功能似乎不适合我在这里,因为我不希望与分工作,它(显然)不具有耐受性的参数。