Rounding to significant figures in numpy

后端 未结 13 1421
无人及你
无人及你 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条回答
  • 2020-12-09 16:44

    I like Greg's very short effective routine above. However, it suffers from two drawbacks. One is that it doesn't work for x<0, not for me anyway. (That np.sign(x) should be removed.) Another is that it does not work if x is an array. I've fixed both of those problems with the routine below. Notice that I've changed the definition of n.

    import numpy as np
    
    def Round_n_sig_dig(x, n):
    
        xr = (np.floor(np.log10(np.abs(x)))).astype(int)
        xr=10.**xr*np.around(x/10.**xr,n-1)   
        return xr    
    
    0 讨论(0)
提交回复
热议问题