Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

python - set very low values to zero in numpy

In numpy I have an array like

[0 +  0.5j, 0.25 + 1.2352444e-24j, 0.25+ 0j, 2.46519033e-32 + 0j] 

what is the fastest and easiest way to set the super low value to zero to get

[0 +  0.5j, 0.25 + 0j, 0.25+ 0j, 0 + 0j] 

efficiency is not the paramount.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Hmmm. I'm not super-happy with it, but this seems to work:

>>> a = np.array([0 +  0.5j, 0.25 + 1.2352444e-24j, 0.25+ 0j, 2.46519033e-32 + 0j])
>>> a
array([  0.00000000e+00 +5.00000000e-01j,
         2.50000000e-01 +1.23524440e-24j,
         2.50000000e-01 +0.00000000e+00j,   2.46519033e-32 +0.00000000e+00j])
>>> tol = 1e-16
>>> a.real[abs(a.real) < tol] = 0.0
>>> a.imag[abs(a.imag) < tol] = 0.0
>>> a
array([ 0.00+0.5j,  0.25+0.j ,  0.25+0.j ,  0.00+0.j ])

and you can choose your tolerance as your problem requires. I usually use an order of magnitude or so higher than

>>> np.finfo(np.float).eps
2.2204460492503131e-16

but it's problem-dependent.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...