irfpy.util.with_context
¶
With statement extension.
With with statement, a code block is wrapperd by a context manager. See also https://docs.python.org/3/library/contextlib.html
Code author: Yoshifumi Futaana
|
This with statement controls the output of numpy array. |
- irfpy.util.with_context.printoptions(*args, **kwds)[source]¶
This with statement controls the output of numpy array.
Use numpy.set_printoptions locally in with-block.
- Params args:
Identical to
numpy.set_printoptions
.- Keywords kwds:
Identical to
numpy.set_printoptions
.
Simple usage is
>>> with printoptions(precision=3, suppress=True): ... print(np.logspace(-3, 3, 5)) [ 0.001 0.032 1. 31.623 1000. ]
Step-by-step explanation follows.
>>> x = np.logspace(-3, 3, 5)
A default output will be
>>> print(x) [1.00000000e-03 3.16227766e-02 1.00000000e+00 3.16227766e+01 1.00000000e+03]
Such output has too much digits, and thus redundunt. Also, sometimes you want to suppress insignificant value like 3.8132234e-17 as 0.
Numpy prepares the functionality,
set_printoptions
, but it will change the numpy feature globally.Therefore, use
printoptions()
. Just do as follows.>>> with printoptions(precision=3, suppress=True): ... print(x) [ 0.001 0.032 1. 31.623 1000. ]
Outside with statement, the print option becomes back.
>>> print(x) [1.00000000e-03 3.16227766e-02 1.00000000e+00 3.16227766e+01 1.00000000e+03]
The code is taken from http://stackoverflow.com/questions/2891790/pretty-printing-of-numpy-array