discretize d^2w/dx^2 = -x(20+ w)(x-3) in javascript

We can discretize the second-order differential equation using the finite difference method. This method approximates the derivatives by the difference between values of the function at neighboring grid points.

Here's the code to discretize d^2w/dx^2 = -x(20+ w)(x-3) with a step size of h using the central difference method.

index.tsx
function discretizeEquation(h, xValues) {
  const n = xValues.length;
  const A = [];

  for (let i = 1; i < n - 1; i++) {
    const xi = xValues[i];
    const xiPlus1 = xValues[i + 1];
    const xiMinus1 = xValues[i - 1];

    const a = (xiPlus1 - xi) / h;
    const b = (xi - xiMinus1) / h;
    const c = -2 / (h * h) - xi * (20 + w(xi));
    A.push([a * a + b * b, -2 * a * a + c, a * a + b * b]);
  }

  return A;
}

function w(x) {
  return 5 * (Math.exp(-x / 2) - Math.exp(-10)) / (1 + Math.exp(-10));
}

const xValues = [...Array(100)].map((_, i) => i * 0.1);
const A = discretizeEquation(0.1, xValues);
611 chars
25 lines

In the example code, we first define the w function which represents our solution. We then create an array of x-values from 0 to 9.9 with a step size of 0.1. Finally, we call the discretizeEquation function with a step size of 0.1 and the array of x-values. The function returns a matrix A which represents our discretized equation.

Note that in the discretized equation, we replace w(xi) with w(x[i]) where xi is the i-th x-value in the array. This means that we are using the values of the function at the grid points as our approximation.

Also, note that in the code we only compute the matrix A. To solve the discretized equation, we would need to compute the right-hand side vector and solve the resulting system of equations.

gistlibby LogSnag