惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hacker News - Newest:
Hacker News - Newest: "LLM"
The Last Watchdog
The Last Watchdog
L
LINUX DO - 最新话题
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Troy Hunt's Blog
Cloudbric
Cloudbric
N
News | PayPal Newsroom
Security Archives - TechRepublic
Security Archives - TechRepublic
TaoSecurity Blog
TaoSecurity Blog
H
Hacker News: Front Page
Help Net Security
Help Net Security
S
Secure Thoughts
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
PCI Perspectives
PCI Perspectives
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
NISL@THU
NISL@THU
Last Week in AI
Last Week in AI
Forbes - Security
Forbes - Security
The GitHub Blog
The GitHub Blog
D
DataBreaches.Net
Scott Helme
Scott Helme
Jina AI
Jina AI
T
Threatpost
W
WeLiveSecurity
P
Palo Alto Networks Blog
F
Fortinet All Blogs
腾讯CDC
人人都是产品经理
人人都是产品经理
云风的 BLOG
云风的 BLOG
博客园 - 【当耐特】
Apple Machine Learning Research
Apple Machine Learning Research
P
Privacy International News Feed
P
Proofpoint News Feed
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
A
About on SuperTechFans
V
Vulnerabilities – Threatpost
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
Cyber Attacks, Cyber Crime and Cyber Security
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
D
Darknet – Hacking Tools, Hacker News & Cyber Security
IT之家
IT之家
美团技术团队
I
InfoQ
阮一峰的网络日志
阮一峰的网络日志
T
Threat Research - Cisco Blogs
博客园 - 司徒正美

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Astrophysics & AI with Python: Simulating Planetary Orbits with Kepler's Laws
Programming Central · 2026-06-17 · via DEV Community

Ever looked up at the night sky and wondered how we know the precise dance of the planets? It’s not magic—it’s math. Specifically, it’s the elegant interplay between Johannes Kepler’s observations and Isaac Newton’s laws of gravity.

But how do we take those centuries-old equations and turn them into a living, breathing simulation on a computer screen?

In this chapter of our journey through computational physics, we are moving from theory to practice. We will bridge the gap between abstract physics and concrete code by building a robust orbital simulator. We'll explore the stability of numerical methods and write Python code that can predict the path of a planet around the Sun with frightening accuracy.

The Physics: From Kepler’s Curves to Newton’s Force

To simulate an orbit, we first need to understand the two pillars of celestial mechanics that make it possible.

1. The Phenomenology: Kepler’s Laws

Johannes Kepler spent years staring at Tycho Brahe’s astronomical data until three distinct patterns emerged. These are the "rules of the road" for the cosmos:

  • The Law of Ellipses: Orbits aren't perfect circles; they are ellipses with the Sun at one focus. This dictates the shape of our simulation.
  • The Law of Equal Areas: A planet speeds up when it's close to the Sun and slows down when it's far away. This dictates the dynamics of the simulation.
  • The Harmonic Law: The relationship between the size of the orbit ( aa ) and the time it takes to complete it ( TT ) is fixed ( T2∝a3T^2 \propto a^3 ). This is our ultimate verification metric.

2. The Causality: Newton’s Gravity

Kepler told us what happens; Newton told us why. His Law of Universal Gravitation provides the engine for our simulation:

F=Gm1m2r2F = G \frac{m_1 m_2}{r^2}

By combining this with Newton's Second Law ( F=maF=ma ), we get the acceleration vector that drives the motion:

a=−GMr2r^\mathbf{a} = -G \frac{M}{r^2} \hat{\mathbf{r}}

This equation is the heart of our code. However, because physics happens in continuous time and computers operate in discrete steps, we have to solve a differential equation numerically. This brings us to the critical challenge of the Two-Body Problem.

The Computational Challenge: Why Stability Matters

Imagine driving in a fog. You know your current speed and direction, so you guess where you'll be in one minute. Then you check your new position and guess again. This is numerical integration.

The simplest way to do this is the Standard Euler Method:

  1. Update Velocity: vnew=vold+aoldΔt\mathbf{v}{new} = \mathbf{v}{old} + \mathbf{a}_{old} \Delta t
  2. Update Position: rnew=rold+voldΔt\mathbf{r}{new} = \mathbf{r}{old} + \mathbf{v}_{old} \Delta t

The Problem: This method is unstable. Over time, it fails to conserve energy. The planet will slowly spiral out into space or crash into the Sun, violating the laws of physics.

The Solution: We will use the Euler-Cromer Method. It’s a tiny tweak with a massive impact. Instead of using the old velocity to update the position, we use the newly calculated velocity:

  1. Update Velocity: vnew=vold+aoldΔt\mathbf{v}{new} = \mathbf{v}{old} + \mathbf{a}_{old} \Delta t
  2. Update Position: rnew=rold+vnewΔt\mathbf{r}{new} = \mathbf{r}{old} + \mathbf{v}_{new} \Delta t (Note the change here!)

This "semi-implicit" approach is symplectic, meaning it keeps the energy error bounded. The orbit remains stable for millions of simulated years.

The Python Simulation Code

Here is the complete Python script to simulate Earth's orbit around the Sun. We use numpy for efficient vector math and matplotlib for visualization.

#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt

# --- 1. PHYSICAL CONSTANTS AND INITIAL SETUP ---

# Gravitational Constant G (SI units: m^3 kg^-1 s^-2)
G = 6.67430e-11
# Mass of the Central Body (Sun) (SI units: kg)
M_sun = 1.989e30

# Initial Conditions (Approximating Earth's orbit at perihelion)
# We use NumPy arrays to represent 2D vectors (x, y)
# Position vector r0 (meters). Placed on the positive x-axis. (~1 AU)
R_AU = 1.496e11 # 1 Astronomical Unit in meters
r0 = np.array([R_AU, 0.0])

# Velocity vector v0 (meters/second). Initial velocity is purely in the y-direction.
V_EARTH = 2.978e4 # Earth's average orbital speed
v0 = np.array([0.0, V_EARTH])

# --- 2. SIMULATION PARAMETERS ---

# Total duration of the simulation (1 Earth year in seconds)
TOTAL_TIME = 365.25 * 24 * 3600
# Time step (dt) for integration (6 hours in seconds). Smaller dt means higher accuracy.
DT = 3600.0 * 6
# Calculate the total number of discrete steps
NUM_STEPS = int(TOTAL_TIME / DT)

# --- 3. DATA STORAGE AND INITIALIZATION ---

# Array to store the X and Y positions at every step.
# Dimensions: (Number of steps, 2 dimensions)
positions = np.zeros((NUM_STEPS, 2))
# Store the initial position in the first row
positions[0] = r0

# Initialize the current state variables for the loop
r_current = r0.copy()
v_current = v0.copy()

# --- 4. ACCELERATION FUNCTION ---

def calculate_acceleration(r_vec, M_central):
    """
    Calculates the acceleration vector (a) due to gravity.
    a = - (G * M / r^2) * r_hat
    """
    # Calculate the magnitude (distance r) using the Euclidean norm
    r_mag = np.linalg.norm(r_vec)

    # Check for division by zero (e.g., if the planet hits the Sun)
    if r_mag == 0:
        return np.zeros(2)

    # Calculate the unit vector pointing from the central body to the planet
    r_hat = r_vec / r_mag

    # Calculate the magnitude of the gravitational acceleration
    # The negative sign ensures the acceleration vector points toward the origin (attraction)
    a_mag = - (G * M_central) / (r_mag**2)

    # The acceleration vector is the magnitude times the unit vector
    return a_mag * r_hat

# --- 5. MAIN INTEGRATION LOOP (Euler-Cromer Method) ---

print(f"Starting simulation: {NUM_STEPS} steps over {TOTAL_TIME/3600/365.25:.2f} years.")

for i in range(1, NUM_STEPS):
    # 5a. Calculate acceleration (a) at the current position (r_current)
    a = calculate_acceleration(r_current, M_sun)

    # 5b. Update velocity (v_current) based on acceleration (a) and time step (DT)
    # This is the 'Euler' part of the update for velocity
    v_current = v_current + a * DT

    # 5c. Update position (r_current) using the *newly calculated* velocity (v_current)
    # This crucial step makes it the 'Cromer' or Semi-Implicit Euler method,
    # which ensures better energy conservation than standard Euler.
    r_current = r_current + v_current * DT

    # 5d. Store the new position vector for plotting
    positions[i] = r_current

print("Simulation complete.")

# --- 6. VISUALIZATION ---

# Scale the positions back to Astronomical Units (AU) for readable plotting
x_au = positions[:, 0] / R_AU
y_au = positions[:, 1] / R_AU

plt.figure(figsize=(8, 8))
# Plot the orbit path
plt.plot(x_au, y_au, label='Simulated Orbit')
# Plot the Sun
plt.plot(0, 0, 'o', color='gold', markersize=10, label='Sun (Origin)')

# Formatting and Display
plt.title(f'Orbital Simulation using Euler-Cromer Integration ({NUM_STEPS} steps)')
plt.xlabel('X Position (AU)')
plt.ylabel('Y Position (AU)')
# Crucially, ensure the aspect ratio is equal so the orbit isn't distorted
plt.gca().set_aspect('equal', adjustable='box')
plt.grid(True, linestyle=':', alpha=0.7)
plt.legend()
plt.show()

Code Breakdown: How It Works

If you are new to numerical physics, the code might look intimidating. Let's break down the logic flow:

  1. Vector Math: We treat position and velocity as vectors (arrays with an x and y component). This allows us to calculate the direction of the gravitational pull easily. np.linalg.norm is the key function here—it calculates the distance rr between the planet and the Sun.
  2. The Acceleration Function: This function implements Newton's law. It takes the position, calculates the distance, finds the unit vector (direction), and scales it by the magnitude of gravity. The negative sign is crucial—it ensures the acceleration points towards the Sun (attraction).
  3. The Main Loop: This is where the magic happens.
    • We calculate acceleration based on where the planet is.
    • We update velocity.
    • The Euler-Cromer Trick: We immediately use that new velocity to update the position. This small change prevents the simulation from "drifting" over time.
  4. Visualization: We convert the raw meters back to Astronomical Units (AU) for a human-readable graph. The command plt.gca().set_aspect('equal') is vital; without it, a perfect circular orbit would look like an ellipse because the x and y scales would be different.

Conclusion: The Digital Cosmos

By implementing the Euler-Cromer method, we have successfully translated the laws of Kepler and Newton into a computational algorithm. We didn't just plot a circle; we simulated the dynamic interplay of forces that keeps the planets in orbit.

This code is more than just a visualization tool—it is a foundation. The principles used here (calculating acceleration, updating state variables, and verifying conservation laws) are the exact same steps used in advanced astrophysics to simulate galaxy collisions, satellite trajectories, and the formation of planetary systems.

Let's Discuss

  1. In the code, we treat the Sun as stationary (infinitely massive). How would you modify the Euler-Cromer loop to account for the Sun's motion if it were not stationary (the true Two-Body Problem)?
  2. If we changed the time step DT to be very large (e.g., 1 day instead of 6 hours), what physical phenomena would you expect to see in the resulting orbit plot?

The concepts and code demonstrated here are drawn directly from the comprehensive roadmap laid out in the ebook
Astrophysics & AI: Building Research Agents for Astronomy, Cosmology, and SETI. You can find it here. Check all the other 50 Programming & AI ebooks with python, typescript, swift, c#: here