1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
#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; } |
Explanation:
- Headers and Constants:
- Includes
iostream
for input and output operations,cmath
for mathematical functions, andiomanip
for formatting. - Defines
g
as the acceleration due to gravity (9.81 m/s²).
- Includes
- Pendulum Structure:
- Represents the pendulum with its
length
,angle
from vertical, andangularVelocity
.
- Represents the pendulum with its
- updatePendulum Function:
- Calculates the angular acceleration using the formula −(g/length)⋅sin(angle)- (g / \text{length}) \cdot \sin(\text{angle}).
- Updates the
angularVelocity
andangle
using simple Euler integration based on the time step (dt
).
- main Function:
- Prompts the user to input the pendulum’s length, initial angle, initial angular velocity, time step, and number of simulation steps.
- Runs a simulation loop where it updates the pendulum’s state and prints the angle at each step.