Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Create Your Own Navier-Stokes Spectral Method Fluid Simulation (With Python)

Philip Mocz
Level Up Coding
Published in
7 min readAug 4, 2023

For today’s recreational coding exercise, we solve the Navier-Stokes equations for an incompressible viscous fluid. To do so, we will implement a spectral method. The Navier-Stokes equations approximately describe the motions of a fluid such as water. The equations can capture the phenomenon of turbulence. The system is also of interest in mathematics as a general proof for the existence and smoothness of solutions in 3D is one of the open Millenium Prize Problems.

You may find the accompanying Python code on GitHub.

Before diving in, below is a gif of what running our simulation looks like:

Navier-Stokes simulation

The Navier-Stokes Equations

We will consider the evolution of the velocity field v(x) of an incompressible fluid with viscosity ν, governed by the Navier-Stokes equations:

Navier-Stokes equations

where P is the fluid pressure. The pressure field in the case of incompressible fluids is special: it is not a separate variable that is evolved in time (unlike in the case of compressible fluids). Instead, the pressure is the solution that keeps the velocity field divergence-free (the second equation). The velocity field experiences advection — the non-linear term on the left-hand side of the first equation — which can cause compression. The fluid also experiences diffusion due to the viscosity coefficient ν. The larger the viscosity coefficient, the ‘stickier’ the fluid becomes, like honey.

Spectral Method

A spectral method represents the numerical solution to a partial differential equation as a sum of global basis functions with coefficients as the unknowns to be solved for. Here we will consider the Fourier basis, which is ideal for representing continuous solutions on a periodic domain. Such a method can then use the Fast Fourier Transform (FFT) algorithm to transform the solution on the physical domain x into Fourier space, where the solution becomes a sum of waves each described by a wavenumber k. We’ve seen this approach in a previous tutorial on solving the time-dependent Schrodinger

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Written by Philip Mocz

Computational Physicist. Sharing intro tutorials on creating your own computer simulations! Harvard ’12 (A.B), ’17 (PhD). Connect with me @PMocz

Responses (7)

Write a response