#include <iostream>
#include <cmath>
#include <iomanip> // For std::fixed and std::setprecision
const double g = 9.81; // Acceleration due to gravity (m/s^2)
// Structure to represent the pendulum
struct Pendulum {
double length; // Length of the pendulum (meters)
double angle; // Angle from vertical (radians)
double angularVelocity; // Angular velocity (radians/second)
};
// Function to update the pendulum's angle and angular velocity using Euler's method
void updatePendulum(Pendulum& pendulum, double dt) {
double angularAcceleration = - (g / pendulum.length) * std::sin(pendulum.angle);
pendulum.angularVelocity += angularAcceleration * dt;
pendulum.angle += pendulum.angularVelocity * dt;
}
int main() {
Pendulum pendulum;
double dt; // Time step for simulation
int steps; // Number of simulation steps
// Input initial conditions
std::cout << "Enter the length of the pendulum (meters): ";
std::cin >> pendulum.length;
std::cout << "Enter the initial angle from vertical (radians): ";
std::cin >> pendulum.angle;
std::cout << "Enter the initial angular velocity (radians/second): ";
std::cin >> pendulum.angularVelocity;
std::cout << "Enter the time step for the simulation (seconds): ";
std::cin >> dt;
std::cout << "Enter the number of simulation steps: ";
std::cin >> steps;
// Simulation loop
std::cout << "Step\tAngle (radians)" << std::endl;
for (int step = 0; step <= steps; ++step) {
std::cout << step << "\t" << std::fixed << std::setprecision(4) << pendulum.angle << std::endl;
updatePendulum(pendulum, dt);
}
return 0;
}