Search code examples
pythonjupyter-notebooksympy

How to set output print precision of Sympy on Jupyter Notebook


Using set_global_settings I was able to print variables on jupyter-notebook using scientific notation:

import sympy as sy
from sympy.printing.str import StrPrinter
StrPrinter.set_global_settings(min=1, max=1)
a=sy.Matrix([189.001234])
a

However, I still need to set precision:

enter image description here


Solution

  • Based on use of .evalf() method described in answer to 'evaluating a sympy function at an arbitrary-precision floating point' and in the SymPy documentation 'Numerical Evaluation':

    import sympy as sy
    from sympy.printing.str import StrPrinter
    StrPrinter.set_global_settings(min=1, max=1)
    a=sy.Matrix([189.001234]).evalf(3)
    a
    

    .evalf() method "takes a precision as the first argument (the default is 15)."

    Alternative with N() function covered in the SymPy documentation 'Numerical Evaluation':

    import sympy as sy
    from sympy.printing.str import StrPrinter
    StrPrinter.set_global_settings(min=1, max=1)
    a=sy.Matrix([189.001234])
    sy.N(a, 3)
    

    Either results in:

    enter image description here