Latex output from sympy does not correctly display in Google Colaboratory Jupyter notebooks

后端 未结 3 1677
夕颜
夕颜 2021-01-11 16:19

I am using Google\'s Colaboratory platform to run python in a Jupyter notebook. In standard Jupyter notebooks, the output of sympy functions is correctly typeset Latex, but

相关标签:
3条回答
  • 2021-01-11 16:36

    You need to include MathJax library before display. Set it up in a cell like this first.

    from google.colab.output._publish import javascript
    url = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=default"
    

    Later, you include javascript(url=url) before displaying:

    x=sp.symbols('x')
    a=sp.Integral(sp.sin(x)*sp.exp(x),x)
    javascript(url=url)
    a
    

    Then, it will display correctly.

    0 讨论(0)
  • 2021-01-11 16:38

    Using colab's mathjax and setting the configuration file to TeX-MML-AM_HTMLorMML worked for me. Below is the code:

    from sympy          import init_printing
    from sympy.printing import latex
    
    def colab_LaTeX_printer(exp, **options):  
        from google.colab.output._publish import javascript 
    
        url_ = "https://colab.research.google.com/static/mathjax/MathJax.js?"
        cfg_ = "config=TeX-MML-AM_HTMLorMML" # "config=default"
    
        javascript(url=url_+cfg_)
    
        return latex(exp, **options)
    # end of def
    
    init_printing(use_latex="mathjax", latex_printer=colab_LaTeX_printer) 
    
    0 讨论(0)
  • 2021-01-11 16:44

    I have just made this code snippet to make sympy works like a charm in colab.research.googlr.com !!!

    def custom_latex_printer(exp,**options):
        from google.colab.output._publish import javascript
        url = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=default"
        javascript(url=url)
        return sympy.printing.latex(exp,**options)
    init_printing(use_latex="mathjax",latex_printer=custom_latex_printer)
    

    Put it after you imported sympy This one basically tell sympy to embed mathjax library using colab api before they actually output any syntax.

    0 讨论(0)
提交回复
热议问题