dln*_*385 12 python floating-point significant-digits representation
我想将一个浮点数表示为一个四舍五入到一些有效数字的字符串,并且从不使用指数格式.基本上,我想显示任何浮点数,并确保它"看起来不错".
这个问题有几个部分:
我已经想出了这样做的一种方法,虽然它看起来像是一种工作,但它并不完美.(最大精度为15位有效数字.)
>>> def f(number, sigfig):
return ("%.15f" % (round(number, int(-1 * floor(log10(number)) + (sigfig - 1))))).rstrip("0").rstrip(".")
>>> print f(0.1, 1)
0.1
>>> print f(0.0000000000368568, 2)
0.000000000037
>>> print f(756867, 3)
757000
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?为什么Python没有内置函数呢?
似乎没有内置的字符串格式化技巧,它允许您(1)打印浮点数,其第一个有效数字出现在小数点后15位,(2)不是科学计数法.这就留下了手动字符串操作.
下面我使用decimal
模块从float中提取十进制数字.该float_to_decimal
函数用于将float转换为Decimal
对象.明显的方法decimal.Decimal(str(f))
是错误的,因为str(f)
可能会丢失有效数字.
float_to_decimal
从十进制模块的文档中解除了.
一旦获得十进制数字作为整数元组,下面的代码就会显而易见:砍掉所需数量的重要数字,必要时向上舍入,将数字连接成一个字符串,粘贴在一个符号上,放置一个小数适当地向左或向右指向零点和零点.
在底部你会发现我用来测试这个f
功能的几个案例.
import decimal
def float_to_decimal(f):
# http://docs.python.org/library/decimal.html#decimal-faq
"Convert a floating point number to a Decimal with no loss of information"
n, d = f.as_integer_ratio()
numerator, denominator = decimal.Decimal(n), decimal.Decimal(d)
ctx = decimal.Context(prec=60)
result = ctx.divide(numerator, denominator)
while ctx.flags[decimal.Inexact]:
ctx.flags[decimal.Inexact] = False
ctx.prec *= 2
result = ctx.divide(numerator, denominator)
return result
def f(number, sigfig):
# http://stackoverflow.com/questions/2663612/nicely-representing-a-floating-point-number-in-python/2663623#2663623
assert(sigfig>0)
try:
d=decimal.Decimal(number)
except TypeError:
d=float_to_decimal(float(number))
sign,digits,exponent=d.as_tuple()
if len(digits) < sigfig:
digits = list(digits)
digits.extend([0] * (sigfig - len(digits)))
shift=d.adjusted()
result=int(''.join(map(str,digits[:sigfig])))
# Round the result
if len(digits)>sigfig and digits[sigfig]>=5: result+=1
result=list(str(result))
# Rounding can change the length of result
# If so, adjust shift
shift+=len(result)-sigfig
# reset len of result to sigfig
result=result[:sigfig]
if shift >= sigfig-1:
# Tack more zeros on the end
result+=['0']*(shift-sigfig+1)
elif 0<=shift:
# Place the decimal point in between digits
result.insert(shift+1,'.')
else:
# Tack zeros on the front
assert(shift<0)
result=['0.']+['0']*(-shift-1)+result
if sign:
result.insert(0,'-')
return ''.join(result)
if __name__=='__main__':
tests=[
(0.1, 1, '0.1'),
(0.0000000000368568, 2,'0.000000000037'),
(0.00000000000000000000368568, 2,'0.0000000000000000000037'),
(756867, 3, '757000'),
(-756867, 3, '-757000'),
(-756867, 1, '-800000'),
(0.0999999999999,1,'0.1'),
(0.00999999999999,1,'0.01'),
(0.00999999999999,2,'0.010'),
(0.0099,2,'0.0099'),
(1.999999999999,1,'2'),
(1.999999999999,2,'2.0'),
(34500000000000000000000, 17, '34500000000000000000000'),
('34500000000000000000000', 17, '34500000000000000000000'),
(756867, 7, '756867.0'),
]
for number,sigfig,answer in tests:
try:
result=f(number,sigfig)
assert(result==answer)
print(result)
except AssertionError:
print('Error',number,sigfig,result,answer)
Run Code Online (Sandbox Code Playgroud)
如果需要浮点精度,则需要使用decimal
模块,该模块是Python标准库的一部分:
>>> import decimal
>>> d = decimal.Decimal('0.0000000000368568')
>>> print '%.15f' % d
0.000000000036857
Run Code Online (Sandbox Code Playgroud)