DEV Community

Yash Matrani
Yash Matrani

Posted on

# Let's simulate gravitational lensing around a black hole in Python

"The black holes of nature are the most perfect macroscopic objects there are in the universe: the only elements in their construction are our concepts of space and time."
— Subrahmanyan Chandrasekhar


There is something deeply unsettling about a black hole. Not because it is massive, or distant, or invisible. But because it represents the point where our understanding of physics simply stops working. The equations that describe everything else in the universe — gravity, light, time — collapse into a singularity at the center, and nobody quite knows what happens next.

I am sixteen years old. I study in the tenth grade. And I find this terrifyingly beautiful.

This article is not a physics paper. It is not a tutorial written by an expert. It is simply an attempt by a student to understand one of the strangest phenomena in the universe by writing code. Because sometimes, reading a formula is not enough. You have to watch it move.


The mathematics of no return

Every black hole has a boundary. It is not a wall, and it is not a surface. It is a distance from the center where the escape velocity — the speed required to break free from the object's gravity — equals the speed of light. Beyond that boundary, nothing escapes. Not matter. Not radiation. Not even light.

This boundary is called the event horizon, and its radius is given by the Schwarzschild equation:
Rs = 2GM / c²

text

Here, G is the gravitational constant, M is the mass of the black hole, and c is the speed of light. It is a deceptively simple equation. Three variables. No calculus. No tensor fields. And yet, it describes the point where space and time break down.

When we plug in real numbers, something remarkable happens. If we compressed the entire Earth into a sphere, its Schwarzschild radius would be just 8.87 millimetres. That is smaller than a marble. The Sun, compressed, would have an event horizon of about 2.95 kilometres — no larger than a small city.

This is the first lesson of black hole physics: the universe is far stranger than it appears.


Three facts that break your intuition

When I first started reading about black holes, I assumed they were simple. A massive object, a strong gravitational pull, and a boundary you cannot cross. But as I went deeper, three ideas in particular challenged everything I thought I understood.

First, time slows down near a black hole. This is not science fiction. It is a direct consequence of general relativity, and it has been experimentally verified. GPS satellites orbiting Earth adjust their clocks every day to account for this effect. Near an event horizon, the dilation becomes extreme. An hour spent close to a black hole could correspond to years on Earth.

Second, black holes spin. Most of them rotate at speeds close to the speed of light. The singularity at the center — usually imagined as a point — becomes a ring. Space itself gets dragged along with the rotation, a phenomenon known as frame dragging. In some ways, this is more difficult to picture than the black hole itself.

Third, black holes are not permanent. In 1974, Stephen Hawking demonstrated that black holes emit radiation and slowly lose mass over time. A stellar-mass black hole would take approximately 10⁶⁷ years to evaporate completely. For comparison, the universe is only 10¹⁰ years old. We are safe — for now.

Each of these facts is counterintuitive on its own. Together, they suggest something profound: the universe does not have to make intuitive sense. It only has to follow the math.


Watching physics come alive through code

Reading about gravitational lensing is one thing. Watching it happen is another. Gravitational lensing is the phenomenon where light bends around a massive object — and in the case of a black hole, it bends so severely that some light never escapes.

To visualize this, I wrote a short Python script. The goal is not to accurately simulate general relativity. That would require solving Einstein's field equations, which is far beyond what a simple script can handle. Instead, the goal is to approximate the bending of light around an event horizon, so that the phenomenon becomes visible to the eye.

Before running the code, install the two necessary libraries:


bash
pip install numpy matplotlib
Then, the script below will compute event horizon sizes for three real objects and render a visualization of light rays bending near a black hole.

python
import numpy as np
import matplotlib.pyplot as plt

# Constants
G = 6.674e-11
c = 3e8

def schwarzschild_radius(mass):
    """Event horizon radius in meters."""
    return (2 * G * mass) / (c ** 2)

# Masses in kg
earth = 5.972e24
sun = 1.989e30
sagittarius_a = 8.6e36  # supermassive black hole at Milky Way center

print("Event horizon sizes:")
print(f"Earth compressed  → {schwarzschild_radius(earth)*1000:.2f} mm")
print(f"Sun compressed    → {schwarzschild_radius(sun)/1000:.2f} km")
print(f"Sagittarius A*    → {schwarzschild_radius(sagittarius_a)/1e9:.2f} million km")

# Gravitational lensing visualization
fig, ax = plt.subplots(figsize=(8, 8))
ax.set_facecolor('black')
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)

# Light rays bending around the black hole
for y in np.linspace(-8, 8, 25):
    x = np.linspace(-10, 0, 200)
    bend = -2 / (1 + np.abs(y) ** 2)
    y_bent = y + bend * (x + 10) / 20
    ax.plot(x, y_bent, color='#ffcc00', alpha=0.4, linewidth=0.7)

# Event horizon
ax.add_patch(plt.Circle((0, 0), 1, color='black', zorder=10))
ax.add_patch(plt.Circle((0, 0), 1.05, color='#ff6b6b', fill=False, linewidth=2))

ax.set_title("Gravitational Lensing Around a Black Hole",
             color='white', fontsize=14, pad=20)
ax.set_xticks([])
ax.set_yticks([])

plt.tight_layout()
plt.show()
When you run this script, you will see something remarkable. The yellow lines represent light rays travelling through space. As they approach the black hole, they begin to curve. The ones that pass closer to the center bend more sharply. Some of them spiral inward and never emerge. The red circle marks the event horizon — the boundary of no return.

This is not a full simulation of relativity. But it captures the essential idea: mass curves space, and light follows the curve.

Why this matters beyond the black hole
In 2019, the Event Horizon Telescope captured the first real image of a black hole — the supermassive object at the center of the galaxy M87. The image looked exactly like the mathematical models had predicted.

Consider what that means. Long before we had the technology to observe a black hole, we knew what it would look like. Because the math told us. Because Einstein's equations, written over a hundred years ago, described something that nobody could see.

This is the power of physics. And this is why I write code — not to replace physics, but to see it in motion.

When I was younger, I used to think that mathematics was a tool for solving problems. Now I understand that it is something much more. It is the language the universe uses to describe itself. Black holes are not anomalies in this description. They are the most extreme examples of it.

What comes next
I am still learning. I am sixteen, and I have barely scratched the surface of what there is to know about general relativity, quantum mechanics, or computational physics. But every simulation I build, every equation I implement, every graph I plot, takes me one step deeper into the subject.

If you are also interested in physics and programming, I would encourage you to do the same. Pick an equation. Pick a phenomenon. Try to simulate it. Break it. Fix it. Change the parameters and watch what happens. That is how understanding grows.

You do not need a supercomputer. You do not need a degree. You need curiosity, and a willingness to sit with confusion until it becomes clarity.

That is all physics has ever required.

If you build something similar, let me know. I would love to see it.

GitHub: github.com/yashmatrani-cpu/My-Projects

Gumroad: yashmatrani.gumroad.com

I am sixteen. Still learning. Sharing what I build.

Tags: #python #physics #science #beginners
Enter fullscreen mode Exit fullscreen mode

Top comments (0)