Set global output precision python

ぃ、小莉子 提交于 2019-12-19 08:15:14

问题


I've written a library of functions to make my engineering homework easier, and use them in the python interpreter (kinda like a calculator). Some return matrices, some return floats.

The problem is, they return too many decimals. For example, currently, when a number is 0, I get an extremely small number as a return (e.g. 6.123233995736766e-17)

I know how to format outputs individually, but that would require adding a formatter for every line I type in the interpreter. I'm using python 2.6.

Is there a way to set the global output formatting (precision, etc...) for the session?

*Note: For scipy functions, I know I can use

scipy.set_printoptions(precision = 4, suppress = True)

but this doesn't seem to work for functions that don't use scipy.


回答1:


What you are seeing is the fact that decimal floating point numbers can only be approximated by binary floating point. See Floating Point Arithmetic: Issues and Limitations.

You could put a module-level variable in your library and use that as the second parameter of round() to round off the return value of the functions in your module, but that is rather drastic.

If you use ipython (which I would recommend for interactive use, much better than the regular interpreter), you can use the 'magic' function %precision.




回答2:


One idea would be to add from __future__ import print_function (at the very top) and then override the standard print function. Here's a very simple implementation that prints floats with exactly two digits after the decimal point:

def print(*args):
    __builtins__.print(*("%.2f" % a if isinstance(a, float) else a
                         for a in args))

You would need to update your output code to use the print function, but at least it will be generic, rather than requiring custom formatting rules in each place. If you want to change how the formatting works, you just need to change the custom print function.




回答3:


With numpy, you could use the set_printoptions method (http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html).

For example:

import numpy as np
np.set_printoptions(precision=4)
print(np.pi * np.arange(8))



回答4:


You could add str methods (assuming you don't already have them) for your number and matrix results, and make them always use the same .format or %f.



来源:https://stackoverflow.com/questions/12439753/set-global-output-precision-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!