[英]How can I print many significant figures in Python?
For a scientific application I need to output very precise numbers, so I have to print 15 significant figures.对于科学应用程序,我需要输出非常精确的数字,因此我必须打印 15 个有效数字。 There are already questions on this topic here, but they all concern with truncating the digits, not printing more .
这里已经有关于这个主题的问题,但它们都与截断数字有关,而不是打印更多。
I realized that the print
function converts the input float
to a 10 character string
.我意识到
print
函数将输入float
转换为 10 个字符的string
。 Also, I became aware of the decimal
module, but that does not suit my needs.此外,我开始意识到
decimal
模块,但这不适合我的需要。
So the question is, how can I easily print a variable amount of signifcant figures of my floats, where I need to display more than 10?所以问题是,我怎样才能轻松地打印我的花车的可变数量的重要数字,我需要显示超过 10 个?
Let:让:
>>> num = 0.0012345
For 3 significant figures :对于3 个有效数字:
>>> f'{num:.3}'
'0.00123'
For 3 decimal places :对于3 个小数位:
>>> f'{num:.3f}'
'0.001'
See the "presentation types for floating point and decimal" table at the bottom of this section for any additional requirements provided by e, E, f, F, g, G, n, %, None
.有关
e, E, f, F, g, G, n, %, None
提供的任何其他要求e, E, f, F, g, G, n, %, None
请参阅本节底部的“浮点和小数的表示类型”表。
You could use the string formatting operator %
:您可以使用字符串格式化运算符
%
:
In [3]: val = 1./3
In [4]: print('%.15f' % val)
0.333333333333333
or str.format()
:或
str.format()
:
In [8]: print(str.format('{0:.15f}', val))
Out[8]: '0.333333333333333'
In new code, the latter is the preferred style, although the former is still widely used.在新代码中,后者是首选风格,尽管前者仍被广泛使用。
For more info, see the documentation .有关更多信息,请参阅文档。
Thought the original question wanted to format n significant figures, not n decimal points.以为原始问题要格式化 n 个有效数字,而不是 n 个小数点。 So a custom function might be required until some more native built-in types are on offer?
因此,在提供更多本机内置类型之前,可能需要自定义函数? So you'll want something like:
所以你会想要这样的东西:
def float_nsf(q,n):
"""
Truncate a float to n significant figures. May produce overflow in
very last decimal place when q < 1. This can be removed by an extra
formatted print.
Arguments:
q : a float
n : desired number of significant figures
Returns:
Float with only n s.f. and trailing zeros, but with a possible small overflow.
"""
sgn=np.sign(q)
q=abs(q)
n=int(np.log10(q/10.)) # Here you overwrite input n!
if q<1. :
val=q/(10**(n-1))
return sgn*int(val)*10.**(n-1)
else:
val=q/(10**n)
return sgn*int(val)*10.**n
To display N significant figures (not decimal places) you use the "g" format:要显示 N 个有效数字(不是小数位),请使用“g”格式:
>>> x = 1.23
>>> print("%.2g" % x)
1.2
>>> x = 12.3
>>> print("%.2g" % x)
12
See format spec for details on precision:有关精度的详细信息,请参阅格式规范:
The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'.
精度是一个十进制数,表示对于用 'f' 和 'F' 格式的浮点值小数点后应显示多少位,或对于用 'g' 格式的浮点值小数点前后应显示多少位或'G'。 For non-number types the field indicates the maximum field size - in other words, how many characters will be used from the field content.
对于非数字类型,该字段指示最大字段大小 - 换句话说,字段内容中将使用多少个字符。 The precision is not allowed for integer values.
整数值不允许使用精度。
Use these two common print idioms for formatting.使用这两种常见的打印习语进行格式化。 Its a matter of personal taste on which is better.
哪个更好看是个人品味的问题。
value = 10/3 #gives a float of 3.33333.....
print '%.15f' % value
print str.format('{0:.15f}', value)
Personally I think the first is more compact and the 2nd is more explicit.我个人认为第一个更紧凑,第二个更明确。 Format has more features when working with multiple vals.
使用多个 val 时,格式具有更多功能。
You could use this function I wrote, it seems to be working fine and it's quite simple !:你可以使用我写的这个函数,它似乎运行良好,而且非常简单!:
def nsf(num, n=1):
"""n-Significant Figures"""
numstr = ("{0:.%ie}" % (n-1)).format(num)
return float(numstr)
Some tests:一些测试:
>>> a = 2./3
>>> b = 1./3
>>> c = 3141592
>>> print(nsf(a))
0.7
>>> print(nsf(a, 3))
0.667
>>> print(nsf(-a, 3))
-0.667
>>> print(nsf(b, 4))
0.3333
>>> print(nsf(-b, 2))
-0.33
>>> print(nsf(c, 5))
3141600.0
>>> print(nsf(-c, 6))
-3141590.0
I hope this helps you ;)我希望这可以帮助你 ;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.