Created
November 1, 2021 14:43
-
-
Save jlapeyre/85b0aa3c5223688ae7f3513ed376744f to your computer and use it in GitHub Desktop.
Replace numbers that are close to zero by zero in arrays and lists.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
ZCHOP_EPS = 1e-12 | |
def zchop_real_np(m, eps=ZCHOP_EPS): | |
m[abs(m) < eps] = 0.0 | |
return m | |
def zchop(m, eps=ZCHOP_EPS): | |
if isinstance(m, float): | |
if abs(m) < eps: | |
return 0.0 | |
return m | |
if isinstance(m, complex): | |
return zchop(m.real) + 1j*zchop(m.imag) | |
if isinstance(m, list): | |
return [zchop(x) for x in m] | |
if isinstance(m, np.ndarray): | |
if m.dtype == 'float64': | |
return zchop_real_np(m) | |
return zchop_real_np(m.real) + 1j * zchop_real_np(m.imag) | |
if isinstance(m, int): | |
if abs(m) < eps: | |
return 0 | |
return m |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment