有没有办法让python以科学记数法打印极大的长片?我说的是大约10 ^ 1000或更大的数字,在这个尺寸下标准打印"%e"%num失败.
例如:
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "%e" % 10**100 1.000000e+100 >>> print "%e" % 10**1000 Traceback (most recent call last): File "", line 1, in TypeError: float argument required, not long
似乎python试图将long转换为float然后打印它,是否有可能让python只用科学记数法打印长而不将其转换为浮点数?
Ale*_*lli 17
gmpy救援......:
>>> import gmpy
>>> x = gmpy.mpf(10**1000)
>>> x.digits(10, 0, -1, 1)
'1.e1000'
Run Code Online (Sandbox Code Playgroud)
当然,我有偏见,作为原作者,仍然是一个提交者gmpy,但我确实认为它可以简化这样的任务,如果没有它可以做一件苦差事(我不知道一个简单的方法没有它一些附加组件,gmpy绝对是我在这里选择的附加组件;-).
无需使用第三方库。这是Python3中的一种解决方案,适用于大整数。
def ilog(n, base):
"""
Find the integer log of n with respect to the base.
>>> import math
>>> for base in range(2, 16 + 1):
... for n in range(1, 1000):
... assert ilog(n, base) == int(math.log(n, base) + 1e-10), '%s %s' % (n, base)
"""
count = 0
while n >= base:
count += 1
n //= base
return count
def sci_notation(n, prec=3):
"""
Represent n in scientific notation, with the specified precision.
>>> sci_notation(1234 * 10**1000)
'1.234e+1003'
>>> sci_notation(10**1000 // 2, prec=1)
'5.0e+999'
"""
base = 10
exponent = ilog(n, base)
mantissa = n / base**exponent
return '{0:.{1}f}e{2:+d}'.format(mantissa, prec, exponent)
Run Code Online (Sandbox Code Playgroud)
这是仅使用标准库的解决方案:
>>> import decimal
>>> x = 10 ** 1000
>>> d = decimal.Decimal(x)
>>> format(d, '.6e')
'1.000000e+1000'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7043 次 |
| 最近记录: |