Generator Public

Code #3401

Earth Orbit Simulation

This C++ program simulates Earth's circular orbit around the Sun by calculating and displaying its position at regular time intervals using trigonometry. It outputs positions to the console with moderate comments explaining the physics and code logic.

C++
// This program simulates Earth's orbit around the Sun in a simplified 2D plane.
// It assumes a circular orbit for simplicity.
// Earth's position is calculated using basic trigonometric functions.

#include <iostream>
#include <cmath> // For sin and cos functions
#include <thread> // For sleep (to simulate time passage)
#include <chrono> // For time delays

int main() {
    const double AU = 149597870700.0; // 1 Astronomical Unit in meters (Earth-Sun distance)
    const double EARTH_ORBITAL_PERIOD = 365.25 * 24 * 3600; // Approximate seconds in a year
    const double TIME_STEP = 86400; // 1 day in seconds (simulation step)
    const int TOTAL_STEPS = 365; // Simulate 1 year

    // Earth's initial position at (AU, 0) assuming circular orbit
    double earth_x = AU;
    double earth_y = 0.0;

    // Angular speed: 2 * PI radians per orbital period
    double omega = 2 * M_PI / EARTH_ORBITAL_PERIOD;

    // Simulation loop for one year
    for (int day = 0; day < TOTAL_STEPS; ++day) {
        // Update position using parametric equations of a circle
        earth_x = AU * cos(omega * day * TIME_STEP);
        earth_y = AU * sin(omega * day * TIME_STEP);

        // Output position (in AU for readability)
        std::cout << "Day " << day + 1 << ": Earth at (" 
                  << earth_x / AU << ", " << earth_y / AU << ") AU" << std::endl;

        // Pause to simulate time passage (adjust for faster/slower simulation)
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    return 0;
}
Prompt: earth orbiting the sun