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 |
#include <iostream> #include <cmath> #include <iomanip> // Constants for the simulation const double PI = 3.141592653589793; const double AMPLITUDE = 1.0; // Maximum displacement from equilibrium const double FREQUENCY = 1.0; // Frequency of oscillation in Hz const double PHASE = 0.0; // Phase shift in radians // Function to calculate the position in Simple Harmonic Motion double calculatePosition(double time) { return AMPLITUDE * std::sin(2 * PI * FREQUENCY * time + PHASE); } int main() { // Simulation parameters double startTime = 0.0; // Start time in seconds double endTime = 10.0; // End time in seconds double timeStep = 0.1; // Time step for the simulation std::cout << "Time (s)\tPosition\n"; std::cout << "-----------------------\n"; // Run the simulation for (double time = startTime; time <= endTime; time += timeStep) { double position = calculatePosition(time); std::cout << std::fixed << std::setprecision(2) << time << "\t\t" << std::fixed << std::setprecision(2) << position << "\n"; } return 0; } |
Explanation
- Constants:
- PI: Mathematical constant π.
- AMPLITUDE: Maximum displacement of the object from its equilibrium position.
- FREQUENCY: The frequency of oscillation in Hertz (Hz).
- PHASE: Phase shift in radians, affecting the initial position of the oscillation.
- Function
calculatePosition(double time)
:- Purpose: Calculates the position of the object at a given time based on Simple Harmonic Motion.
- Formula: Uses the equation
position = AMPLITUDE * sin(2 * π * FREQUENCY * time + PHASE)
to compute the position.
- Main Function:
- Simulation Parameters:
startTime
: Starting time for the simulation.endTime
: Ending time for the simulation.timeStep
: Time increment for each simulation step.
- Simulation Loop:
- Iterates from
startTime
toendTime
, calculating and printing the position of the object at each time step.
- Iterates from
- Simulation Parameters:
Usage
- SHM Simulation: Models the oscillatory motion of an object based on Simple Harmonic Motion principles.
- Position Calculation: Uses trigonometric functions to calculate and print the position of the object over time.