A Javascript Library for Finite Difference Method (FDM)
Fig. 1. Comparison of analytical and numerical solution of the user-defined function f(x) using fdm.js.
// define f(x)
function f(x) { return Math.exp(0.11 * x) * Math.sin(x); }
// solve 1st derivative of f(x)
const fdm = new FDM();
fdm.dh = 0.1;
const g = fdm.grad(f);
The fdm.js is a simple JavaScript library that enables you to calculate the 1st and 2nd derivatives of user-defined functions. It utilizes the Finite Difference Method (FDM), which is a commonly employed differentiation technique in computer simulation.
This library focuses on being "easy to use" and "lightweight." Developers now have enhanced capabilities for conducting numerical simulations quickly and effortlessly.
First, link fdm.js to your page by adding the following line to HTML header.
<script src="fdm.js"></script>
Next, define a function you'd like to differentiate.
const f = x => x * x;
Create an instance of fdm.js and set the step size.
const fdm = new FDM();
fdm.dh = 0.1;
You can also specify `fdm.accuracy` to increase the accuracy.
e.g. fdm.accuracy = 1, 2, 3, ...
The algorithm is derived from Bengt(1988).
fdm.accuracy = 2;
Finally, wrap the function with grad
or lap
to create derivative functions.
const g = fdm.grad(f); // gradient
console.log(g(1) - 2*1);
console.log(g(2) - 2*2);
const h = fdm.lap(f); // laplacian
console.log(h(1) - 2);
console.log(h(2) - 2);
The above example illustrates a one-dimensional case, but this library can support up to three dimensions.
<html>
<head>
<script src="fdm.js"></script>
</head>
<body>
<script>
// define f(x)
const f = x => x * x;
// setup fdm.js
const fdm = new FDM();
fdm.dh = 0.1;
fdm.accuracy = 2;
// gradient
const g = fdm.grad(f);
console.log(g(1) - 2*1);
console.log(g(2) - 2*2);
// laplacian
const h = fdm.lap(f);
console.log(h(1) - 2);
console.log(h(2) - 2);
</script>
</body>
</html>
The following examples are calculated by fdm.js.
Fig. 2. Comparison of analytical and numerical solution of f(x) = x**3.
Fig. 3. Comparison of analytical and numerical solution of f(x) = sqrt(x).
Fig. 4. Comparison of analytical and numerical solution of f(x) = exp(x).
Fig. 4. Comparison of analytical and numerical solution of f(x) = sin(x).
MIT License.