Skip to content

Speeding up Generators

Steven Clontz edited this page Nov 9, 2023 · 1 revision

Thanks to the power of SageMath, this is a very tempting pattern:

# generator.sage
class Generator(BaseGenerator):
    def data(self):
        x = var("x")

        a,b = sample(range(2,10),2)

        f = sin(a*x)/(b*x)

        lim = limit(f, x=0)

        return {
            "f": f,
            "lim": lim,
        }
<?xml version='1.0' encoding='UTF-8'?>
<!-- template.xml -->
<knowl mode="exercise" xmlns="https://spatext.clontz.org" version="0.2">
    <content>
        <p>Find the limit: <m>\lim_{x\to 0} {{f}}</m></p>
    </content>
    <outtro>
        <p><m>{{lim}}</m></p>
    </outtro>
</knowl>

BUT. By doing Math™, you can drastically speed the generaiton step up:

# generator.sage
class Generator(BaseGenerator):
    def data(self):
        x = var("x")

        a,b = sample(range(2,10),2)

        f = sin(a*x)/(b*x)

        # nah fam, don't do this:
        # lim = limit(f, x=0)

        # instead, do this:
        lim = Integer(a)/b    # Integer(a) prevents float arithmetic

        return {
            "f": f,
            "lim": lim,
        }

In particular, while you can use SageMath functions like limit, diff, and so on, if you know the function you're manipulating, generating exercises will be quicker if you write out the known limit/derivative symbolically than rely on SageMath to do the math for you.

According to this test you might speed up your code by over three orders of magnitude...

Clone this wiki locally