天天看點

在LaTeX中優雅地插入Wolfram Mathematica代碼

本文同步在如何高效地聯合使用 Mathematica 和 LaTeX?。

插入一般的代碼使用listings包或minted包即可,但是Mathematica代碼在前端中的顯示是其實際的文本代碼的再渲染,如果直接插入會插入許多多餘的代碼,即使手動選擇其中的公式代碼,其效果也比較差。

方法一:

使用Wolfram Mathematica的另存為功能另存為PDF,即可直接使用\includegraphics指令以圖檔形式插入PDF:

\includegraphics[width=1\textwidth]{1.pdf}
           

更好的方式是另存為PostScript (.ps) 檔案,然後手動将.ps檔案的檔案字尾名改為.eps,即可直接使用\includegraphics指令插入EPS圖檔:

\includegraphics[width=1\textwidth]{1.eps}
           

方法二:

結合使用MathematicaCellsToTeX和mmacells。首先在Wolfram Mathematica中執行

[email protected]"http://github.com/jkuczm/MathematicaCellsToTeX/releases/download/v0.2.2/CellsToTeX-0.2.2.paclet"
           

安裝CellsToTeX,但是安裝後執行

[email protected]"CellToTeX`"
           

有問題。根據How best to embed various cell groups into a LATEX project?在Wolfram Mathematica中執行

[email protected]"https://raw.githubusercontent.com/jkuczm/MathematicaCellsToTeX/master/NoInstall.m"
SetOptions[CellToTeX, "CurrentCellIndex" -> Automatic];
ExportString[
 NotebookGet[] /. 
  cell : Cell[_, __] :> Cell[CellToTeX[cell], "Final"], "TeX", 
 "FullDocument" -> False, "ConversionRules" -> {"Final" -> Identity}]
           

即可生成大段的mmacells的LaTeX代碼,粘貼到LaTeX檔案中的相應位置,然後在LaTeX文檔開頭添加

\usepackage{mmacells}
           

然後将mmacells克隆到本地,将其中的mmacells.sty檔案複制到與LaTeX檔案同一個檔案夾下,或者如果要反複使用的話可以放到TEXMF目錄下,對于Windows 10 TeXLive 2020而言,應在TEXLIVE安裝目錄下\texlive\2020\texmf-dist\tex\latex建立mmacells檔案夾并将mmacells.sty檔案複制到該檔案夾下,在CMD或PowerShell中執行

texhash
           

指令後即可編譯,效果如下圖所示:

在LaTeX中優雅地插入Wolfram Mathematica代碼

注意:如果在beamer等環境中使用mmacells需指定frame類型為fragile:

\begin{frame}[fragile]{幀标題}{副标題}
\end{frame}
           

(參考FancyVerb Error in using minted package with beamer)