How to print a lot of significant numbers in Python?

For a scientific application, I need to output very accurate numbers, so I have to print 15 significant numbers. There are already questions on this topic, but they all relate to truncating numbers, not printing anymore.

I realized that the print function converts the input float to 10 characters string . In addition, I became aware of the decimal module, but this does not meet my needs.

So the question is, how can I easily print a variable number of significant digits of my floats, where do I need to display more than 10?

+8
python
source share
4 answers

You can use the % line format operator:

 In [3]: val = 1./3 In [4]: print('%.15f' % val) 0.333333333333333 

or str.format() :

 In [8]: print(str.format('{0:.15f}', val)) Out[8]: '0.333333333333333' 

In the new code, the latter is the preferred style, although the former is still widely used.

See the documentation for more information .

+12
source share

I thought the original question wanted to format n significant digits, not n decimal points. So a custom function might be needed until some additional built-in types are suggested? So you need 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 sf and trailing zeros, but with a possible small overflow. """ sgn=npy.sign(q) q=abs(q) n=int(npy.log10(q/10.)) # Here you overwrite input n! if q<1. : val=q/(10**(n-1)) else: val=q/(10**n) return sgn*int(val)*10.**n 
+8
source share

Use these two common print idioms for formatting. This is a matter of personal taste, which is better.

 value = 10/3 #gives a float of 3.33333..... print '%.15f' % value print str.format('{0:.15f}', value) 

Personally, I think that the first is more compact, and the second is more explicit. The format has more features when working with multiple vals.

+3
source share

You can use this function that I wrote, it works fine, and it is pretty simple !:

 def nsf(num, n=1): """n-Significant Figures""" numstr = ("{0:.%ie}" % (n-1)).format(num) return float(numstr) 
  • First, it converts a number to a string using the exponent notation
  • Then returns it as a float .

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 

Hope this helps you;)

+1
source share

All Articles