Nerdamer Scripting

Scripting examples

Each example is a complete script. Paste it into the Playground, or pass it to nerdamer(...).

Speed: a loop in Scripting runs slower than the same loop in JavaScript. For heavy numeric work, write the loop in JavaScript and call Nerdamer for the mathematics.

Evaluate a periodic solution family

solve can return a whole family of solutions. For sin(x)=0 it returns {_n*pi}, where _n is any integer. Store the solutions with :, then pick one by giving _n a value.

sol: solve(sin(x),x);
evaluate(sol,{_n=>0})

The result is {0}. The value for _n applies only to this evaluate call; _n itself can't be assigned. Use : to store the result: sol = solve(sin(x),x) is an error, because = makes an equation.

Newton's method for a nonlinear system

This example finds every real root of three nonlinear equations with Newton's method, started from several points. jacobian builds the matrix of partial derivatives once. Each step of newton evaluates it at the current point with evaluate(value, variables, point) and rounds the new point to 20 digits.

Based on the multivariable Newton method described in Courtney Remani, Numerical Methods for Solving Systems of Nonlinear Equations, Lakehead University.

In JavaScript: the same example in JavaScript has the same functions, with the loops in TypeScript.
jacobian(residuals,variables):=
    let(
        n:count(variables),
        J:imatrix(n),
        row:0,
        col:0,
        block(
            for(row:0, row<n, row:row+1,
                for(col:0, col<n, col:col+1,
                    J[row,col]:diff(residuals[row],variables[col]))),
            J
        )
    );

newton(residuals,variables,J,point,steps):=
    let(
        step:0,
        block(
            for(step:0, step<steps, step:step+1,
                point:numeric(
                    point-invert(evaluate(J,variables,point))
                        *evaluate(residuals,variables,point),
                    20)),
            point
        )
    );

isRoot(residuals,variables,point,tolerance):=
    let(
        values:evaluate(residuals,variables,point),
        dot(values,values)<tolerance^2
    );

findRoots(residuals,variables,J,seeds,steps,tolerance):=
    let(
        solutions:{},
        block(
            each(seeds,a, each(seeds,b, each(seeds,c,
                let(
                    point:iferror(newton(residuals,variables,J,[a,b,c],steps),[]),
                    if(count(point),
                        if(isRoot(residuals,variables,point,tolerance),
                            solutions:union(solutions,{numeric(point,8)}),
                            0),
                        0)
                )))),
            solutions
        )
    );

residuals:[x^2+y^2+z^2-14, x*y+y*z+z*x-11, x*y*z-6];
variables:[x,y,z];
J:jacobian(residuals,variables);
findRoots(residuals,variables,J,[0,2,4],12,1e-8)

The 27 starting points made from [0,2,4] reach all six permutations of [1,2,3]. A start where the Jacobian can't be inverted is skipped by iferror. Roots are rounded to 8 digits and collected in a set with union, so a root found twice is kept once.

Derive the normal modes of coupled oscillators

Two identical masses connected by three springs have symmetric and antisymmetric normal modes. This scripting version builds the symbolic mass and stiffness matrices, solves the characteristic equation, and derives a normalized nullspace basis for each mode.

Follow the same physical system in McGill University's PHYS 232 notes: Coupled oscillators — 2 masses and 3 springs.

In JavaScript: see the same calculation in JavaScript.
modeShape(dynamic,eigenvalue):=
    let(
        basis:nullspace(
            evaluate(dynamic,{q=>eigenvalue})
        ),
        shape:basis[0],
        return(shape/shape[0])
    );

normalModes():=
    let(
        K:matrix(
            [k+kappa,-kappa],
            [-kappa,k+kappa]
        ),
        M:matrix(
            [m,0],
            [0,m]
        ),
        dynamic:K-M*q,
        characteristic:factor(determinant(dynamic)),
        eigenvalues:solve(characteristic,q),
        frequencies:[
            simplify(eigenvalues[0]^(1/2)),
            simplify(eigenvalues[1]^(1/2))
        ],
        modes:[
            modeShape(dynamic,eigenvalues[0]),
            modeShape(dynamic,eigenvalues[1])
        ],
        return([
            characteristic,
            eigenvalues,
            frequencies,
            modes
        ])
    );

assume(k>0);
assume(m>0);
assume(kappa>0);

normalModes()

The returned value contains the factored characteristic expression, the two eigenvalues (omega^2), their square roots, and the normalized mode shapes. The assumptions restrict the symbolic parameters to positive values, as in the JavaScript version.

Where to go next

See the Nerdamer Scripting reference for the constructs used above, or the JavaScript versions of these examples.