Guides

JavaScript examples

Longer programs that use Nerdamer inside a JavaScript or TypeScript algorithm. Nerdamer does the mathematics: expressions, derivatives, exact algebra, vectors and matrices, determinants, solving, evaluation, row reduction and nullspaces. Your code runs the algorithm around it.

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. Nerdamer builds the symbolic Jacobian and evaluates it; the loops are ordinary TypeScript.

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

import { Expression, type ParserValuesObject } from 'nerdamer/core';
import { diff } from 'nerdamer/calculus';
import { Matrix, ValuesSet, Vector, dot, invert } from 'nerdamer/structures';

function jacobian(residuals: Expression[], variables: string[]): Matrix {
    const rows = residuals.map(residual =>
        variables.map(variable => diff(residual, variable))
    );
    return new Matrix(...rows);
}

// Gives each variable its coordinate in the point.

function valuesAt(variables: string[], point: Vector): ParserValuesObject {
    return Object.fromEntries(
        variables.map((variable, i) => [variable, point.getExpressionAt(i)])
    );
}

// Rounds each coordinate to the given number of digits.

function round(point: Vector, digits: number): Vector {
    return Vector.create(
        Array.from({ length: point.count() }, (_, i) =>
            point.getExpressionAt(i).toDecimal(digits)
        )
    );
}

function newton(
    residuals: Expression[],
    variables: string[],
    J: Matrix,
    point: Vector,
    steps: number
): Vector {
    for (let step = 0; step < steps; step++) {
        const values = valuesAt(variables, point);
        const F = Vector.create(residuals.map(residual => residual.evaluate(values)));
        const Jn = J.map(entry => entry.evaluate(values));

        // x_(n+1) = x_n - J(x_n)^-1 F(x_n). Rounding keeps the numbers

        // small: exact fractions would double in size with every step.

        point = round(point.minus(invert(Jn).times(F)), 20);
    }
    return point;
}

function isRoot(
    residuals: Expression[],
    variables: string[],
    point: Vector,
    tolerance: number
): boolean {
    const values = valuesAt(variables, point);
    const F = Vector.create(residuals.map(residual => residual.evaluate(values)));
    return dot(F, F).lt(tolerance ** 2);
}

function findRoots(
    residuals: Expression[],
    variables: string[],
    J: Matrix,
    seeds: number[],
    steps: number,
    tolerance: number
): ValuesSet {
    // A set keeps each root once.

    const solutions = new ValuesSet();

    for (const a of seeds) {
        for (const b of seeds) {
            for (const c of seeds) {
                let point: Vector;
                try {
                    point = newton(residuals, variables, J, Vector.create([a, b, c]), steps);
                } catch {
                    continue; // The Jacobian is singular on the way.

                }
                if (!isRoot(residuals, variables, point, tolerance)) continue;

                solutions.add(round(point, 8));
            }
        }
    }
    return solutions;
}

const residuals = [
    'x^2+y^2+z^2-14',
    'x*y+y*z+z*x-11',
    'x*y*z-6'
].map(residual => Expression.create(residual));

const variables = ['x', 'y', 'z'];
const J = jacobian(residuals, variables);
const solutions = findRoots(residuals, variables, J, [0, 2, 4], 12, 1e-8);

console.log('Jacobian:');
console.log(J.text());
console.log('Solutions:');
for (const solution of solutions) {
    console.log(`    ${solution.text()}`);
}

// Output:

// Jacobian:

// matrix([2*x, 2*y, 2*z], [y+z, x+z, x+y], [y*z, x*z, x*y])

// Solutions:

//     [1.0, 2.0, 3.0]

//     [1.0, 3.0, 2.0]

//     [2.0, 1.0, 3.0]

//     [2.0, 3.0, 1.0]

//     [3.0, 1.0, 2.0]

//     [3.0, 2.0, 1.0]

Each step rounds the point to 20 digits with toDecimal. Without it, Newton's method on exact fractions doubles the number of digits with every step, and starts far from a root take seconds each. Roots are rounded to 8 digits and collected in a ValuesSet, so a root found twice is kept once.

In Scripting: the same example in Nerdamer Scripting has the same functions, with the loops in Scripting.

Derive the normal modes of coupled oscillators

Two identical masses connected by three springs have symmetric and antisymmetric normal modes. Instead of recognizing those modes by inspection, this example lets Nerdamer derive them from the symbolic mass and stiffness matrices.

Follow the same physical system in McGill University's PHYS 232 notes: Coupled oscillators — 2 masses and 3 springs. The notes first derive the two equations of motion and then introduce the matrix method for larger systems.

The assumptions say that the masses and spring constants are positive, as in the physical system.

import { factor, simplify } from 'nerdamer/algebra';
import { Expression } from 'nerdamer/core';
import { solve } from 'nerdamer/solve';
import { Matrix, Vector } from 'nerdamer/structures';
import { assume } from 'nerdamer/assumptions';

// Masses and spring constants are positive.

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

// K x = omega^2 M x. Use q = omega^2 while solving.

const K = new Matrix(
    ['k+kappa', '-kappa'],
    ['-kappa', 'k+kappa']
);

const M = new Matrix(
    ['m', 0],
    [0, 'm']
);

const q = Expression.create('q');
const dynamic = K.minus(M.times(q));
const characteristic = factor(dynamic.determinant());
const eigenvalues = solve(characteristic, 'q');

function modeShape(eigenvalue: Expression): Vector {
    const [basis] = dynamic
        .map(entry => entry.evaluate({ q: eigenvalue }))
        .nullspace();

    // Normalize the mode so its first coordinate is 1.

    const scale = basis[0];

    return Vector.create(
        basis.map(entry => entry.div(scale))
    );
}

const frequencies = eigenvalues.elements.map(eigenvalue =>
    simplify(eigenvalue.pow('1/2'))
);

const modes = eigenvalues.elements.map(modeShape);

console.log('Characteristic equation:');
console.log(`${characteristic.text()} = 0`);

console.log('Normal modes:');
eigenvalues.elements.forEach((eigenvalue, index) => {
    console.log(`Mode ${index + 1}:`);
    console.log(`    omega^2 = ${eigenvalue.text()}`);
    console.log(`    omega = ${frequencies[index].text()}`);
    console.log(`    shape = ${modes[index].text()}`);
});


// Output:

// Characteristic equation:

// (k-m*q)*(2*kappa+k-m*q) = 0

// Normal modes:

// Mode 1:

//     omega^2 = k*m^-1

//     omega = (m^-1*k)^(1/2)

//     shape = [1, 1]

// Mode 2:

//     omega^2 = m^-1*(2*kappa+k)

//     omega = (m^-1*(k+2*kappa))^(1/2)

//     shape = [1, -1]

Where to go next

Browse the JavaScript / TypeScript API for the functions and classes used above, or use the Playground for Nerdamer notation and scripting.