问题
How is the threshold for scientific notation set in an ipython notebook? I want to set all number outisde of something like [0.01, 100] to be printed in scientific notation, but the threshold seems to be much higher. i.e.
In [165]: x = sympy.Symbol('x'); 1.e8*x
Out[165]: 100000000.0*x
but
In [166]: 1.e28*x
Out[166]: 1.0e+28*x
Because I'm using sympy, I can't send the number to a formatted print statement, i.e.
In [167]: print "%.2e" % (1.e8*x)
ERROR: TypeError: float argument required, not Mul [IPython.core.interactiveshell]
回答1:
I believe it depends on the precision of the underlying Float object.
SymPy uses mpmath to provide arbitrary precision floating point numbers. The default precision is 15 digits, but you can set any precision. It looks like it uses scientific notation when it can't represent the whole number using the given precision. You can force a given precision to be used by constructing the Float object directly:
In [30]: Float('100', 3)
Out[30]: 100.
In [31]: Float('1000', 3)
Out[31]: 1.00e+3
However, note that this will affect other things as well. All digits past three will be rounded.
In [32]: Float('1.23456', 3)
Out[32]: 1.23
If you don't want the extra zeros before the e+
part, you can pass in a setting the the string printer:
In [45]: from sympy.printing.str import StrPrinter
In [44]: StrPrinter({'full_prec': False}).doprint(Float('10000000', 5))
Out[44]: '1.0e+7'
This changes the string printer, which is what is used by sstr
or print
. It looks like the LaTeX printer, which is what you probably want to use in the notebook, does this automatically.
We should add an easier way to set this, without changing the precision. The options are there in mpmath, they just aren't exposed in the SymPy printers. I've opened https://github.com/sympy/sympy/issues/7847 for this.
来源:https://stackoverflow.com/questions/25222681/scientific-exponential-notation-with-sympy-in-an-ipython-notebook