JSFiddle - React, Tailwind, and code Playground

by jrj2211

HTML

<script src="
https://cdn.jsdelivr.net/npm/[email protected]/lib/browser/math.min.js
"></script>

JavaScript

// Constants
const L = 18.5;
const L1 = 20;
const L2 = 15;
const d = 5;

// Helper functions
const cos = Math.cos;
const sin = Math.sin;
const pow = Math.pow;

// Define the system of equations
function equations(vars) {
    const [theta1, theta2, y] = vars;

    const x1 = -L + L1 * cos(theta1);
    const y1 = L1 * sin(theta1);
    const x2 = L + L2 * cos(theta2);
    const y2 = L2 * sin(theta2);

    const eq1 = pow(x1 - x2, 2) + pow(y1 - y2, 2) - pow(2 * L, 2);
    const eq2 = pow((x1 + x2) / 2, 2) + pow(((y1 + y2) / 2) - y, 2) - pow(d, 2);

    // Avoid division by zero in slopes
    const dx = x2 - x1;
    const dy = y2 - y1;
    const midpointSlope = ((y2 + y1) / 2 - y) / ((x2 + x1) / 2);
    const eq3 = dx !== 0 ? midpointSlope * (dy / dx) + 1 : 0; // Handle vertical line edge case

    return [eq1, eq2, eq3];
}

// Compute the Jacobian matrix
function jacobian(vars) {
    const [theta1, theta2, y] = vars;

    const x1 = -L + L1 * cos(theta1);
    const y1 = L1 * sin(theta1);
    const x2 = L + L2 * cos(theta2);
    const y2 = L2 * sin(theta2);

    const dx1_dtheta1 = -L1 * sin(theta1);
    const dy1_dtheta1 = L1 * cos(theta1);
    const dx2_dtheta2 = -L2 * sin(theta2);
    const dy2_dtheta2 = L2 * cos(theta2);

    // Partial derivatives for eq1
    const dEq1_dTheta1 = 2 * (x1 - x2) * dx1_dtheta1 + 2 * (y1 - y2) * dy1_dtheta1;
    const dEq1_dTheta2 = 2 * (x1 - x2) * -dx2_dtheta2 + 2 * (y1 - y2) * -dy2_dtheta2;
    const dEq1_dY = 0;

    // Partial derivatives for eq2
    const dEq2_dTheta1 = 2 * ((x1 + x2) / 2) * (dx1_dtheta1 / 2) +
                         2 * (((y1 + y2) / 2) - y) * (dy1_dtheta1 / 2);
    const dEq2_dTheta2 = 2 * ((x1 + x2) / 2) * (dx2_dtheta2 / 2) +
                         2 * (((y1 + y2) / 2) - y) * (dy2_dtheta2 / 2);
    const dEq2_dY = -2 * (((y1 + y2) / 2) - y);

    // Partial derivatives for eq3
    const dx = x2 - x1;
    const dy = y2 - y1;
    const slopeMidX = (x2 + x1) / 2;
    const slopeMidY = ((y2 + y1) / 2) - y;

 ...