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
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])