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

推荐订阅源

Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Vercel News
Vercel News
Microsoft Azure Blog
Microsoft Azure Blog
Stack Overflow Blog
Stack Overflow Blog
Martin Fowler
Martin Fowler
Hacker News - Newest:
Hacker News - Newest: "LLM"
Cyberwarzone
Cyberwarzone
Recorded Future
Recorded Future
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threat Research - Cisco Blogs
Know Your Adversary
Know Your Adversary
Recent Announcements
Recent Announcements
L
LINUX DO - 热门话题
D
DataBreaches.Net
K
Kaspersky official blog
T
Threatpost
F
Full Disclosure
T
The Exploit Database - CXSecurity.com
C
CERT Recently Published Vulnerability Notes
S
Securelist
I
Intezer
有赞技术团队
有赞技术团队
罗磊的独立博客
爱范儿
爱范儿
S
Schneier on Security
P
Privacy & Cybersecurity Law Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
L
LangChain Blog
美团技术团队
G
Google Developers Blog
T
Tor Project blog
Project Zero
Project Zero
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Hacker News
The Hacker News
W
WeLiveSecurity
Engineering at Meta
Engineering at Meta
Apple Machine Learning Research
Apple Machine Learning Research
aimingoo的专栏
aimingoo的专栏
PCI Perspectives
PCI Perspectives
L
LINUX DO - 最新话题
MyScale Blog
MyScale Blog
阮一峰的网络日志
阮一峰的网络日志
酷 壳 – CoolShell
酷 壳 – CoolShell
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
P
Proofpoint News Feed
Webroot Blog
Webroot Blog
T
Troy Hunt's Blog

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: Unlocking the Secrets of N-Body Simulations with Rebound
Programming Central · 2026-06-18 · via DEV Community

The universe is a relentless clockwork governed by a single, ubiquitous force: gravity. From the tight dance of binary stars to the majestic spiral arms of galaxies, all motion is dictated by the pairwise gravitational attraction between massive bodies. While the principles of Newtonian mechanics are elegantly simple, the computational task of modeling the motion of many interacting objects—known as the N-Body Problem—rapidly escalates from a solvable physics equation to a profound mathematical and computational challenge.

This guide shifts our focus from analyzing static astrophysical datasets to the dynamic, predictive modeling of gravitational systems. We are moving from descriptive statistics to predictive kinematics, requiring specialized, high-precision tools like the REBOUND simulation package.

The Theoretical Hurdle: Why Gravity is Hard

To understand why we need specialized tools, we must first grasp the inherent instability of gravitational systems.

The Chaos of Three Bodies

When N=2N=2 (the two-body problem, e.g., Earth orbiting the Sun), the system is analytically solvable. The equations of motion yield precise, closed-form solutions described by Keplerian ellipses.

However, as soon as we introduce a third body ( N=3N=3 ), the analytical certainty vanishes. The system becomes sensitive to initial conditions—a hallmark of deterministic chaos. Minuscule changes in starting position or velocity can lead to wildly divergent outcomes over long timescales. Therefore, predicting the evolution of complex planetary systems is only possible through numerical integration.

The Computational Scaling Crisis: O(N2)O(N^2)

The second hurdle is raw computational power. For a system of NN bodies, every body interacts with every other body. The number of unique pairwise interactions scales quadratically:

P=N(N−1)2P = \frac{N(N-1)}{2}

This O(N2)O(N^2) complexity means that doubling the number of bodies quadruples the calculation time. While techniques like Barnes-Hut approximations can reduce this for galaxy-scale simulations, they sacrifice the precision required for modeling the long-term stability of planetary systems.

The Instability Crisis: Why Standard Integrators Fail

Even with perfect force calculations, standard numerical methods (like Runge-Kutta) fail for astrophysics because they don't respect the fundamental physics of the system. Gravitational systems are Hamiltonian: they must conserve total energy and angular momentum. Standard integrators introduce "numerical drift," causing orbits to expand or decay artificially.

The solution is Symplectic Integrators. These algorithms are designed to preserve the geometric structure of Hamiltonian dynamics, ensuring that errors do not accumulate over billions of steps. This is non-negotiable for long-term stability studies.

Introducing REBOUND: The Gold Standard

Given these challenges, standard Python libraries (like scipy.integrate.solve_ivp) are insufficient. Enter REBOUND (Recursive Bound), a powerful, C-based simulation framework with a robust Python interface.

REBOUND is engineered specifically for gravitational dynamics, offering:

  • Specialized Integrators: Including WHFast (symplectic, for long-term stability) and IAS15 (adaptive, for high-precision close encounters).
  • Hierarchical Time Stepping: Efficiently managing systems where bodies require different time steps.
  • Data Generation: It is the perfect tool to generate synthetic datasets for training AI models to predict system stability.

Tutorial: Simulating Earth's Orbit with Python

Let's dive into the code. We will set up the simplest stable N-body system: the Earth orbiting the Sun. We will use REBOUND to integrate this system for one year and verify the stability of the orbit.

Prerequisites

Ensure you have the library installed:

pip install rebound numpy

The Python Code

This script initializes the simulation, adds the Sun and Earth, integrates the motion, and prints the final orbital parameters to verify accuracy.

import rebound
import numpy as np
import sys

# Ensure the simulation runs silently and efficiently
rebound.set_status(sys.stdout, color=False)

# --- 1. Simulation Initialization and Setup ---
sim = rebound.Simulation()
sim.units = ('AU', 'Msun', 'year')  # Standard celestial mechanics units
sim.integrator = "IAS15"            # High-precision adaptive integrator
sim.dt = 0.001                      # Initial timestep

# --- 2. Adding Particles ---
# Particle 0: The Sun (Mass = 1.0 Solar Mass)
sim.add(m=1.0)

# Particle 1: Earth (Mass ~ 3e-6 Solar Masses)
# Defined via Keplerian elements: Semi-major axis = 1.0 AU, Eccentricity = 0.0167
sim.add(m=3.003e-6, a=1.0, e=0.0167)

# --- 3. Stabilization ---
# Move the system to the Center of Mass frame to prevent drift
sim.move_to_com()

# --- 4. Integration Loop ---
T_end = 1.0      # Simulate for 1 year
N_steps = 100    # Record 100 data points
times = np.linspace(0, T_end, N_steps)

print(f"Starting simulation for {T_end} year(s)...")

for i, t in enumerate(times):
    sim.integrate(t)
    # We could store positions here, but we will verify stability at the end

# --- 5. Verification & Output ---
print("\n--- Simulation Results ---")
print(f"Final Time reached: {sim.t:.6f} years")

# Access the final state of the Earth (Particle 1)
final_earth = sim.particles[1]

print("\nFinal State of Earth:")
print(f"Position (x, y, z): ({final_earth.x:.6f}, {final_earth.y:.6f}, {final_earth.z:.6f}) AU")
print(f"Velocity (vx, vy, vz): ({final_earth.vx:.6f}, {final_earth.vy:.6f}, {final_earth.vz:.6f}) AU/year")

# Verify orbital parameters (should be close to initial values)
print(f"\nFinal Semi-Major Axis (a): {final_earth.a:.6f} AU")
print(f"Final Eccentricity (e): {final_earth.e:.6f}")

# Check Energy Conservation (Crucial for Symplectic Integrators)
sim.integrate(T_end) # Ensure we are at the exact end time
e_start = -0.000000000000000 # Theoretical energy of this system
e_end = sim.calculate_energy()
print(f"\nEnergy Conservation Check:")
print(f"Total Energy at End: {e_end:.12f}")

Detailed Code Explanation

1. Initialization and Environment

sim = rebound.Simulation()
sim.units = ('AU', 'Msun', 'year')
sim.integrator = "IAS15"

We instantiate the Simulation object. Setting units to AU, Solar Masses, and Years is crucial for numerical stability; it normalizes the gravitational constant GG to 4π24\pi^2 , avoiding floating-point issues with meters and seconds. We select the IAS15 integrator, a high-order adaptive method perfect for high-precision planetary simulations.

2. Adding Particles

sim.add(m=1.0)
sim.add(m=3.003e-6, a=1.0, e=0.0167)

REBOUND allows adding particles via Cartesian coordinates or Keplerian elements. Here, we define the Sun at the origin (implied) and Earth using orbital elements ( aa = semi-major axis, ee = eccentricity). REBOUND automatically calculates the necessary initial velocity vectors.

3. Stabilization

sim.move_to_com()

This is a critical step. It shifts the entire system so that the Center of Mass (COM) is at (0,0,0)(0,0,0) and total momentum is zero. Without this, the system would drift through space due to numerical errors, which can destabilize long integrations.

4. Integration and Verification

The loop integrates the system forward. At the end, we check the particles attribute. sim.particles[1] gives us the state of the Earth.

The most important verification is Energy Conservation. In a closed gravitational system, total energy must remain constant. If sim.calculate_energy() shows a significant difference between start and end, the simulation has failed (likely due to a timestep that is too large or a non-suitable integrator). For our 1-year simulation, the energy should be conserved to machine precision.

Conclusion: Bridging Physics and AI

Mastering REBOUND allows us to run controlled virtual experiments on the universe. This capability is the foundation of modern computational astrophysics.

More importantly, these simulations are the "ground truth" for Artificial Intelligence. By using REBOUND to generate massive datasets of planetary systems—labeling them as "stable" or "unstable"—we can train machine learning models to predict the fate of newly discovered exoplanets in seconds, rather than running billion-year simulations. This synergy between high-precision physics and predictive AI is where the future of astrophysics lies.

Let's Discuss

  1. If you were to simulate a multi-planet system (like our Solar System) for 1 billion years, which integrator would you choose (IAS15 or WHFast) and why?
  2. How would you use the data generated by REBOUND to train a neural network to detect unstable exoplanet systems? What features (orbital elements) would be most important?

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