Scientific/Exponential notation with sympy in an ipython notebook

谁都会走 提交于 2021-01-27 23:11:00

问题


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

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