How can I print many significant figures in Python?

后端 未结 6 1970
独厮守ぢ
独厮守ぢ 2020-12-16 12:53

For a scientific application I need to output very precise numbers, so I have to print 15 significant figures. There are already questions on this topic here, but they all c

6条回答
  •  星月不相逢
    2020-12-16 13:26

    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)
    
    1. It first converts the number to a string using exponent notation
    2. Then returns it as 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
    

    I hope this helps you ;)

提交回复
热议问题