Skip to content

Commit 773a150

Browse files
committed
update round_signif, almost_unique
1 parent a9ad4de commit 773a150

File tree

1 file changed

+31
-21
lines changed

1 file changed

+31
-21
lines changed

misc.py

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
__all__ = ['slicer', 'keys', 'argmax_nd', 'argmin_nd', 'indexed', 'argclip', 'amap',
77
'atleast_nd', 'assign_first', 'assign_last', 'dyadic', 'altcumsum', 'altcumprod',
8-
'extend_linspace', 'extend_geomspace', 'round_sigfig', 'unique_sigfig',
8+
'extend_linspace', 'extend_geomspace', 'round_signif', 'almost_unique',
99
'siground', 'DictToClass', 'DefaultDictToClass']
1010

1111

@@ -335,40 +335,50 @@ def extend_geomspace(x, min=None, max=None):
335335
return np.exp(extend_linspace(np.log(x), ln_min, ln_max))
336336

337337

338-
def round_sigfig(x, n=6):
338+
def round_signif(x, decimals):
339339
"""
340-
Round array for given significant figures.
341-
Added: 2022-10-19.
340+
Round to the given number of significant figures.
341+
ref: Scott Gigante, https://stackoverflow.com/a/59888924/2144720
342342
343-
x:
344-
Input number or array.
345-
n:
346-
Number of digit
343+
Added: 2022-10-19, Updated: 2022-10-20
344+
345+
x : array_like
346+
Input data.
347+
decimals : int, optional
348+
Number of decimal places to round to.
347349
"""
348-
xarr = np.asfarray(x)
349-
str = np.array2string(xarr, separator=',', formatter={'float_kind': lambda x: f"{x:.{n}e}"})
350-
xnew = eval(f"np.array({str}, dtype=xarr.dtype)")
351-
if np.isscalar(x):
352-
return xnew.item()
353-
else:
354-
return xnew
350+
x = np.asfarray(x)
351+
x_pos = np.where(np.isfinite(x) & (x != 0), np.abs(x), 10**(decimals))
352+
mags = 10**(decimals - np.floor(np.log10(x_pos)))
353+
return np.around(x * mags) / mags
355354

355+
# obsolete:
356+
# x = np.asfarray(x)
357+
# str = np.array2string(x, separator=',', formatter={'float_kind': lambda x: f"{x:.{decimals}e}"})
358+
# return eval(f"np.array({str}, dtype=x.dtype)")
356359

357-
def unique_sigfig(x, n=6, **kwargs):
360+
361+
def almost_unique(x, nrel=10, nabs=None, **kwargs):
358362
"""
359-
Find the unique elements of an array for given significant figures.
363+
Find the unique elements of an array for given precision.
360364
Added: 2022-10-19.
361365
362366
x:
363367
Input number or array.
364-
n:
365-
Number of digit
368+
nrel:
369+
Number of decimals in scientific notation (significant figures - 1).
370+
nabs:
371+
Number of absolute decimals.
366372
kwargs:
367373
np.unique arguments, including 'return_index', 'return_inverse',
368374
'return_counts', 'axis'
369375
"""
370-
xnew = round_sigfig(x, n=n)
371-
return np.unique(xnew, **kwargs)
376+
if nrel is not None:
377+
x = round_signif(x, decimals=nrel)
378+
if nabs is not None:
379+
x = np.around(x, decimals=nabs)
380+
381+
return np.unique(x, **kwargs)
372382

373383

374384
def siground(x, n):

0 commit comments

Comments
 (0)