Rounding to significant figures in numpy

后端 未结 13 1499
无人及你
无人及你 2020-12-09 16:00

I\'ve tried searching this and can\'t find a satisfactory answer.

I want to take a list/array of numbers and round them all to n significant figures. I have written

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 16:20

    Okay, so reasonably safe to say this is not allowed for in standard functionality. To close this off then, this is my attempt at a robust solution. It's rather ugly/non-pythonic and prob illustrates better then anything why I asked this question, so please feel free to correct or beat :)

    import numpy as np
    
    def round2SignifFigs(vals,n):
        """
        (list, int) -> numpy array
        (numpy array, int) -> numpy array
    
        In: a list/array of values
        Out: array of values rounded to n significant figures
    
        Does not accept: inf, nan, complex
    
        >>> m = [0.0, -1.2366e22, 1.2544444e-15, 0.001222]
        >>> round2SignifFigs(m,2)
        array([  0.00e+00,  -1.24e+22,   1.25e-15,   1.22e-03])
        """
    
        if np.all(np.isfinite(vals)) and np.all(np.isreal((vals))):
            eset = np.seterr(all='ignore')
            mags = 10.0**np.floor(np.log10(np.abs(vals)))  # omag's
            vals = np.around(vals/mags,n)*mags             # round(val/omag)*omag
            np.seterr(**eset)
            vals[np.where(np.isnan(vals))] = 0.0           # 0.0 -> nan -> 0.0
        else:
            raise IOError('Input must be real and finite')
        return vals
    

    Nearest I get to neat does not account for 0.0, nan, inf or complex:

    >>> omag      = lambda x: 10**np.floor(np.log10(np.abs(x)))
    >>> signifFig = lambda x, n: (np.around(x/omag(x),n)*omag(x))
    

    giving:

    >>> m = [0.0, -1.2366e22, 1.2544444e-15, 0.001222]
    >>> signifFig(m,2)
    array([ nan, -1.24e+22,   1.25e-15,   1.22e-03])
    

提交回复
热议问题