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 ret
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.
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))
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.
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.