18

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.

0

5 Answers 5

10

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.

10

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))
3
  • Will this alter only print output precision; not accuracy of the stored variable values?
    – Sumax
    Aug 26, 2019 at 13:43
  • Because it sets the Numpy printing options.
    – Marc
    Aug 26, 2019 at 16:48
  • 1
    Also useful is np.printoptions() in a shorter context block, see example in doc Apr 28, 2022 at 14:58
8

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.

3
  • 1
    I only want to format the print output, not the precision of the variables themselves (I need the accuracy for calculations, but the printout can be rounded). Ipython looks like what I want, thanks! Sep 15, 2012 at 22:04
  • the link for %precision is broken. Sep 17, 2015 at 16:34
  • @ofloveandhate Thanks for the heads-up. It works again now. Sep 17, 2015 at 17:20
1

Building on @Blckknght solution, we could use regex for something a bit more robust.

import re

round_to = 4

def str_round(match):
    return str(round(eval(match.group()), round_to))

def print(*args, **kwargs):
    if len(args):
        args = list(args)
        for i, text in enumerate(args):
            text = str(text)
            if re.search(r"([-+]?\d*\.?\d+|[-+]?\d+)", text):
                args[i] = re.sub(r"([-+]?\d*\.?\d+|[-+]?\d+)", str_round, text)

    return __builtins__.print(*args, **kwargs)

Now the number in the following print statement will get rounded

>>> print(f"The number {1/3} is in this sentence.")
The number 0.3333 is in this sentence.
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.