Skip to main content

Section 4 Sage (and more) in PTX

Let's do some math in PTX.

Subsection 4.1

There isn't that much to say about math markup. Suffice to say that multiline stuff is harder, but anything that MathJax supports is easy. See the sample article and PreTeXt guide.

We get \(\int_0^\infty e^{-x}dx=1\) with <m>\int_0^\infty e^{-x}dx=1</m>.

We get

\begin{equation*} \int_0^\infty e^{-x}dx=1 \end{equation*}

with <me>\int_0^\infty e^{-x}dx=1</me>.

Subsection 4.2 Sage

The Author Guide has some documentation on how to use Sage cells. But let's see this in action.

I hope the output is not a surprise. Let's see the code, though.

<sage>
  <input>2+2</input>
  <output>5</output>
</sage>

What happened here? Good thing I can use Sage to doctest my Sage examples!

You can do much more interesting things that this, of course. Imagine we have just defined the sum of divisors function

\begin{equation*} \sigma(n)=\sum_{d|n,d>0}d \end{equation*}
  1. First, students should do it ‘by hand’. Have fun. Any patterns? Probably notice something about primes …

  2. But then it gets tedious. Is there ever a number which has sum of divisors three times itself?

And here is the code.

        <sage>
          <input>@interact
def _(n=[1..200]):
    print("Sum is {}".format(sigma(n)))
    print("Divide by n and you get {}".format(sigma(n)/n.n()))</input>
          <output></output>
        </sage>

Here is the code for something that can be autogenerated with the pretext script. Note the <sageplot> tag.

<figure xml:id="figure-sage-power-table-1">
  <caption>Colored table of powers modulo <m>n=11</m></caption>
  <image xml:id="sageplot-sage-power-table-1" width="60%">
    <description>Colored table of powers modulo <m>n=11</m></description>
    <sageplot>
    import matplotlib.pyplot as plt
    from matplotlib.ticker import IndexLocator, FuncFormatter
    p = 11
    mycmap = plt.get_cmap('gist_earth',p-1)
    myloc = IndexLocator(floor(p/5),.5)
    myform = FuncFormatter(lambda x,y: int(x+1))
    cbaropts = {  'ticks':myloc, 'drawedges':True, 'boundaries':srange(.5,p+.5,1)}
    matrix_plot(matrix(p-1,[mod(a,p)^b for a in range(1,p) for b in srange(p)]), cmap=mycmap,colorbar=True, colorbar_options=cbaropts, ticks=[myloc,myloc], tick_formatter=[None,myform])
    </sageplot>
  </image>
</figure>