11

How can I modify the point at which python decides to print in scientific notation?

E.g. I'd like everything > 1e4 or < 1e-4 to be printed in scientific notation.

Good:

In [11]: 5e20
Out[11]: 5e+20

Bad:

In [12]: 5e10
Out[12]: 50000000000.0
DilithiumMatrix
  • 17,795
  • 22
  • 77
  • 119

1 Answers1

16

In IPython you can use

%precision %.4g

this will print floating point values who's absolute value is < 1e-4 or >= 1e4 in scientific notation.

You can find more information about the %precision command in the IPython API Docs. For string formatting options have a look at the Python Docs

wjandrea
  • 28,235
  • 9
  • 60
  • 81
zabbarob
  • 1,191
  • 4
  • 16
  • 25
  • Awesome, thanks! (Note: I don't think there should be quotations there). Is there anyway to make this the default behavior (or load it everytime I run ipython)? – DilithiumMatrix May 31 '13 at 23:56
  • 1
    Add (or edit) the line `c.InteractiveShellApp.exec_lines = ['%precision %.4g']` in IPython's configuration file. To locate the file use `ipython locate`. In my case it was under `~/.ipython/profile_default/ipython_config.py` (see [IPython Doc](http://ipython.org/ipython-doc/stable/config/overview.html#ipython-dir)). Thanks for pointing out the quotations, I'll remove them :-). – zabbarob Jun 01 '13 at 01:11
  • 2
    This solution no longer seems to work (IPython 2.2.0 / RHEL7 / Python 2.7.5). It continues to print out scientific notation for values that do not meet my requested threshold. – dg99 Jan 30 '15 at 17:29
  • 1
    I just tried it out with Python 2.7.9 and IPython 2.4.0 and it still works for me. – zabbarob Jan 31 '15 at 02:41
  • This is a [Jupyter "magic" instruction](https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-precision), and does not work for Python used in Spyder. – mins Jul 21 '23 at 16:41