damped oscillation in javascript

Damped oscillations occur when an object oscillates back and forth under a damping force, eventually coming to rest due to the dissipation of energy. Here's an implementation of damped oscillation in JavaScript:

index.tsx
// Define constants
const k = 0.5; // Spring constant
const m = 1; // Mass
const c = 0.5; // Damping coefficient

// Define initial conditions
let x = 0.5; // Position
let v = 0; // Velocity
let a = 0; // Acceleration

// Define time step and simulation duration
const dt = 0.01; // Time step
const tEnd = 10; // Simulation duration

// Simulate damped oscillation
for (let t = 0; t <= tEnd; t += dt) {
  // Calculate acceleration
  a = (-k * x - c * v) / m;

  // Update velocity and position
  v += a * dt;
  x += v * dt;

  // Print position at each time step
  console.log(`t = ${t.toFixed(2)}, x = ${x.toFixed(2)}`);
}
624 chars
27 lines

In this example, we define the constants for the spring constant, mass, and damping coefficient. We then define the initial conditions for the position, velocity, and acceleration. We also define the time step and simulation duration.

In the for loop, we calculate the acceleration, update the velocity and position, and print the position at each time step. We use the -k * x term to model the restoring force of the spring, and the -c * v term to model the damping force.

This implementation can be modified to incorporate other types of oscillation, such as forced oscillations or chaotic oscillations.

gistlibby LogSnag