🛠️ToolsShed

Moon Phase Calculator

Calculate the current moon phase, illumination percentage, and lunar cycle information for any date.

Pertanyaan yang Sering Diajukan

Implementasi Kode

import math
from datetime import date, datetime

def calculate_moon_phase(year: int, month: int, day: int) -> dict:
    """
    Calculate moon phase using the Conway algorithm.
    Returns phase name, illumination percentage, and age in days.
    """
    # Julian date calculation
    if month <= 2:
        year -= 1
        month += 12

    A = int(year / 100)
    B = 2 - A + int(A / 4)
    julian = int(365.25 * (year + 4716)) + int(30.6001 * (month + 1)) + day + B - 1524.5

    # Days since known new moon (Jan 6, 2000)
    known_new_moon = 2451549.5
    lunation = 29.53058868

    age = (julian - known_new_moon) % lunation
    illumination = (1 - math.cos(2 * math.pi * age / lunation)) / 2

    # Phase name
    phases = [
        (0.03, "New Moon"), (0.22, "Waxing Crescent"), (0.28, "First Quarter"),
        (0.47, "Waxing Gibbous"), (0.53, "Full Moon"), (0.72, "Waning Gibbous"),
        (0.78, "Last Quarter"), (0.97, "Waning Crescent"), (1.00, "New Moon")
    ]
    fraction = age / lunation
    phase_name = next(name for threshold, name in phases if fraction <= threshold)

    return {
        "age_days": round(age, 2),
        "illumination_pct": round(illumination * 100, 1),
        "phase": phase_name,
        "fraction": round(fraction, 4)
    }

result = calculate_moon_phase(2024, 1, 15)
print(f"Phase: {result['phase']}")
print(f"Age: {result['age_days']} days")
print(f"Illumination: {result['illumination_pct']}%")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.