
This course includes our updated coding exercises so you can practice your skills as you learn.
See a demo
Learn Python and Jupyter notebooks, install Python, and explore NumPy arrays, visualization, and numerical methods for derivatives, integrals, and differential equations in physics simulations.
Learn how to install Python using the free Anaconda individual edition, set up the graphical installer, and use Anaconda Navigator with Jupyter Notebook for Python programming.
Jupyter notebook offers an easy, browser-based way to learn Python with selectable kernels and runnable cells, emphasizing cell execution order and the option to restart and run all.
Explore how to style Jupyter notebooks with markdown, headings, italics, and images, rename notebooks, and create text cells to explain and share your work openly.
Download the template files, watch the videos, and code along to learn by doing. Compare your notebook with the instructor's notebook and download the notes book to reinforce Python concepts.
Learn how to apply style sheets to Jupyter notebooks using Jupiter themes, install and switch themes like Monarch, troubleshoot permissions by running as administrator, and manage kernels for accessible visuals.
Learn to use PyCharm Community for large Python projects: install, create new projects and interpreters, and run Python scripts, noting .py workflow versus notebooks.
Explore Visual Studio Code as a versatile editor for both Jupyter notebooks and native Python files, with color highlighting and kernel selection, while Jupyter notebooks remain the course's primary tool.
Update or install Python packages using Anaconda Navigator and editors like Jupyter, PyCharm, and VS Code; inspect installed packages, Python version, and the base environment.
Explore core Python basics in this optional crash course, covering a numbers module, streams, lists and arrays as vectors and matrices, loops, if statements, file I/O, and plotting with ModCloth.
Import numpy as np to access constants like pi and e and perform basic mathematics. Use operators +, -, *, /, //, % and numpy sqrt for square roots.
Learn about Python's numeric data types: integers, floats, and complex numbers, and how automatic type promotion, casting, and complex arithmetic enable physics computations.
Explore strings in Python by creating literals and variables, measure their length with len(), and concatenate with + while converting numbers to strings with str.
Learn how to use Python lists to store numbers and strings, index from zero, slice, append, remove, and sort, including multi-dimensional lists, and understand their math and memory limits.
Learn to create and manipulate NumPy arrays from Python lists, index elements and build multidimensional arrays, and perform elementwise operations like multiplication and addition using axis 0 or 1.
Compute the dot and cross products of vectors with numpy, calculate norms and perform component wise operations, then multiply matrices, and determine determinants and inverses.
Explore Python dictionaries as key-value stores, learn to access values by keys, list keys and values, and update or add entries such as brand, model, year, and country.
Explore how loops and if statements work in Python, including while and for loops, using range, modulus for even/odd checks, iterating over lists and strings, and storing results.
Discover practical methods to save and load data in Python. Save entire lists with a text format or write data line-by-line, then load using loadtxt.
Define your own functions in Python or Nampai using def, arguments, and return. Build a dot product for three-component vectors and compare positional and keyword arguments.
Master plotting with matplotlib to visualize data and results: create scatter plots from x, y, and z coordinates, add labels, plot functions, customize axes, combine plots, and save figures.
Learn to visualize three-dimensional data with density or contour plots in Python, using two-dimensional coordinates, meshgrid, and z-values to create height maps with legends and color bars.
Learn to create 3D data visualizations in Python by using contour 3D and plot 3D with projection, color maps, and axis limits, including parametric and scatter plots for 3D space.
Celebrate completing this crash course and prepare for the next section on the numériques and physics, revisiting the syntax of if statements and loops.
Explore fitting a function to data, starting with Taylor series, then interpolation with linear and cubic splines, and finally fitting a physical model by minimizing error for later applications.
Explore the Taylor expansion of the exponential function, noting all derivatives equal the function itself, forming a polynomial around x0. Truncate with a chosen max for accuracy.
Explore the Taylor expansion of the sine function around zero, deriving odd terms from derivatives 0, 1, and -1, and observe how more terms improve accuracy.
Learn to define and compute first and higher numerical derivatives using a small step h, implement a general derivative function, and verify with a Taylor expansion approach.
Define and implement the general Taylor expansion to approximate any function using numerically computed derivatives, step size, and finite terms, exploring error trade-offs near the expansion point.
Explore using a third-order polynomial to interpolate data, generate synthetic data with noise, and fit model coefficients to recover the correct parameters, illustrating data fitting in physics.
The lecture compares linear and cubic spline interpolation for fitting data in Python, showing linear splines connect points with straight segments, while cubic splines ensure smooth, continuous derivatives.
Explore cubic spline interpolation to fit perturbed data, compare unperturbed versus perturbed plots, and learn to smooth data by tuning the smoothing factor for a physics-relevant fit.
Explore high-order polynomial interpolation and solving linear systems to fit multiple data points with a single polynomial, using a design matrix and numpy.linalg.solve, and note extrapolation limits.
Fit a polynomial model by selecting coefficients a_k in a sum of x^k to describe data with thermal fluctuations. Iteratively adjust parameters to minimize error and align model with data.
Define a polynomial model with coefficients a0, a1, a2 and a3, test with starting values, and compute error fit using squared differences between data and model points from -5 to 5.
Calculate the gradient of the error with respect to each coefficient using the chain rule, then apply gradient descent to iteratively update parameters and minimize the error.
apply gradient descent to update polynomial coefficients in a data fit, iterating through iterations to minimize error and compare fitted coefficients to true values while plotting the fit against data.
Master data fitting and interpolation by applying a physically relevant function to a dataset, and preview how this approach will analyze a system of coupled harmonic oscillators.
Explore numerical derivatives in Python using forward, backward, central differences, and Richardson extrapolation, with a car motion example for velocity and acceleration; extend to gradients, curls, and divergences.
Explore the mathematical definition of a derivative, using difference quotients, forward, backward, and central schemes, and show how the slope at a point equals the limit as h approaches zero.
Implement numerical derivatives in Python using forward, backward, and central difference methods, compare to analytical derivative, and demonstrate why central differences offer greater accuracy with NumPy and Matplotlib.
Explore why the central differences method in numerical differentiation achieves second-order accuracy in computational physics, unlike forward or backward differences, via Taylor expansions and big-O analysis.
Explore how Richardson methods improve first-derivative accuracy beyond central difference by including farther points, achieving higher-order error cancellation at the cost of more computations.
Explore calculating the second derivative using forward, backward, and central finite-difference methods, including double and mixed schemes, and improve accuracy with Richardson extrapolation.
Compute velocity and acceleration from a 1000-point position data set using forward differences, central differences, and Richardson methods; determine the maximum acceleration and its time from the data.
Compute velocity and acceleration from time-series data using forward, central, and Richardson difference methods in Python. Analyze errors and identify the maximum acceleration and its time.
Explore multi-dimensional derivatives with the nabla operator, computing gradient, curl, and divergence for scalar and vector fields; implement central-difference gradients and verify against analytic results using code.
Explore multidimensional derivatives by computing divergence and curl of a vector field with central differences on Gx, Gy, Gz and step size h, then compare to analytical solutions.
Explore derivatives in Python, compare the Richardson method with forward differences, and apply to velocity and acceleration from position versus time data, then examine gradient, curl, and divergence.
Learn numerical integration methods for higher accuracy after derivatives, and apply these concepts to rotational energy, moment of inertia, the magnetic field of a charged wire, and Fourier transform-based eigenfrequencies.
Learn basic numerical integration by comparing rectangle and trapezoid methods, addressing endpoint effects, and using discrete data from -3 to 3 to approximate area under a curve.
Explore discretizing integrals with the trapezoidal method, compare it to a rectangular sum, and implement linear-spline based integration for equidistant and non-equidistant Python data.
Enhance accuracy by using Simpson's rule with Newton-Cotes, which interpolates data with a third-order polynomial and integrates it for higher precision than trapezoidal method, noting need for odd data points.
Explore rotational motion of a point mass on a circular orbit with Python, computing x=r cos(ω t) and y=r sin(ω t), plotting 2D/3D paths, and deriving kinetic energy ½ m v².
Explore how to model the rotation of extended objects by building a stick rotating around one end, compute moment of inertia, and compare analytical and numerical results using Python.
Rotate the stick about its center, plot the shifted configuration, and compare numerical results with the analytical solution by integrating from -s/2 to s/2, and computing the kinetic energy.
Learn how to rotate a stick around its center in Python and compare numerical results to the analytical kinetic energy using the moment of inertia.
This lecture derives the analytical moment of inertia for a sphere about its center, i = 2/5 m r^2, using cylindrical coordinates and volume density, and compares to numerical methods.
Compute the rotational energy by summing contributions from points inside a sphere. Loop over a cube, discard outside points, and normalize to total mass to compare with the analytical result.
Learn to model a hollow spherical shell's rotation by adapting the solid-shell method, compute analytical inertia with inner and outer radii, and validate with a numerical plot and rotational energy.
Explore a Python-based approach to rotating a hollow spherical shell and compare its rotational energy to a solid sphere, focusing on moment of inertia and mass considerations.
Compute the magnetic field of a z-axis current-carrying wire via magnetostatics and the vector potential, using a numerical approach and comparing to the analytical limit.
Define the current density for the wire and build coordinate arrays with a mesh grid for x and y, focusing on z-axis integration. Exclude zeros to avoid division by zero.
Compute the vector potential of a charged wire by numerically integrating along the wire's axis with a circular cross-section, compare to analytic results, and verify convergence.
Compute the magnetic field of a charged wire from its vector potential using curl and central differences, compare numerical results with the analytical toroidal field, and visualize with arrow plots.
Create a 3d quiver plot of the magnetic field around a wire in Python, scaling vector components and adjusting figure size to reveal the toroidal field.
Learn to decompose a superposition of three oscillations into individual frequencies using the Fourier transform, comparing it with straightforward integration and the trapezoidal method in Python.
Explore the Fourier transform to extract frequency components from a time signal, implement the integral with trapezoidal method, and identify peaks in the intensity spectrum.
Illustrates the intensity spectrum with peaks at 0.3, 2, and 3.5 from a superposition of two or three oscillators, using fft and a faster amp dot 50 50 transform.
Review integral methods with varying accuracy for data-set calculations and apply them to rotational energy, moment of inertia, and magnetic field of a charged wire, with differentiation and Fourier transform.
Explore differential equations by combining differentiation and integration with numerical methods. Compare accuracy and speed, and apply these methods to radioactive decay, free fall, and pendulum in one dimension.
Introduce the Euler method for solving first order differential equations, derive y(t+h) ≈ y(t) + h f(t,y), and propagate solutions in time with a Python implementation.
Radioactive decay is modeled by the differential equation dy/dt = -y; implement Euler's method in Python to propagate, compare with the analytic exponential solution, and plot results.
Define an Euler method function in Python to solve differential equations, with arguments f, t0, y0, max, and h. Test the function on an example, returning and plotting the solution.
Apply the Euler method to dy/dt = -8 t y, demonstrating time amplified decay and a gaussian in time, with numerical results matching the analytical solution.
Transform second-order differential equations into a system of first-order equations to apply the Euler method. Learn to model higher-order dynamics, such as acceleration, with starting values and code in Python.
Solve a second-order free fall using the Euler method by converting to first-order equations. Contrast results with the analytic solution y0 + v0 t - 1/2 g t^2.
Apply the Euler method to solve the pendulum as a damped second-order ODE. Use the small-angle approximation to obtain the analytic cosine solution and compare it with the numerical result.
This lecture demonstrates solving the pendulum's accurate differential equation, comparing small-angle approximations to full dynamics, showing how larger starting angles require numerical integration with smaller steps to reveal differences.
Add damping and driving forces to the pendulum model and analyze how the external sine forcing, damping, and omega influence the numerical solution, convergence, and potential chaotic and periodic behavior.
Use SciPy solve_ivp to solve ordinary differential equations more accurately than Euler methods. Explore RK45, compare results to older methods, and set time spans and initial conditions.
Explore solving higher order and second order differential equations with solve_ivp, using AKI 45 with adaptive step size to obtain accurate results from few points, outperforming Euler methods.
Compare the performance and accuracy of differential equation solvers, such as RK45, RK23, and other IVP methods in Python, using a pendulum model and plotting results to assess deviations.
Explore the fourth order Runge–Kutta method for solving differential equations, including implementing RK4 with intermediate k-values and comparing it to Euler methods and RK4–5 variants.
Extend the archive to five methods to implement rk45, using higher-order coefficients and k-term combinations for fifth-order accuracy, then compare with rk4 methods.
Compare Euler, rk4, and rk45 methods for solving a first-order differential equation, showing rk4 and rk45 achieve much higher accuracy than Euler in a two-time amplified decay example.
Review the first part on differential equations, highlighting numerical methods and simple examples like radioactive decay, freefall, and the pendulum, and previewing multidimensional examples with multiple objects.
Explore solving multi-dimensional differential equations with multiple bodies, from rolling balls and a Lorenz system to heat conduction and the three body problem, including spacecraft trajectories.
Explore a two-dimensional differential equation by modeling a ball in a bowl as two uncoupled harmonic oscillators, using a quadratic potential and first-order reformulation to solve and visualize the dynamics.
The lecture demonstrates solving a two-dimensional rolling ball differential equation by converting a second-order system into four first-order equations, then analyzing X and Y trajectories and circular motion.
Explore how changing starting velocity and introducing an external periodic force transform linear motion into spiral and elliptical trajectories, solved numerically for a two-dimensional ball system.
Explore the Lorenz chaos model as a three-coupled differential system for X, Y, and Z, illustrating chaotic solutions, butterfly effect, and how deterministic laws yield sensitive dependence on initial conditions.
Implement the Lorenz equations, define x, y, z with their right-hand sides, solve the IVP, and compare nearby initial conditions to illustrate chaotic butterfly dynamics.
Explore solving the Lorenz differential equation in Python, showing how decreasing parameter b below a critical value removes chaos, yielding deterministic trajectories from near-identical starts.
Describe how heat evolves in a spatial region with the heat equation, using a one-dimensional bar or higher dimensions, and apply central differences to the second derivative.
Demonstrates implementing the one-dimensional heat equation with finite-difference in Python, building the right-hand side function, applying boundary conditions, solving with solve_ivp, and visualizing results with density plots.
Solve the two dimensional heat equation on a 100×100 grid using the La Plus operator, flatten arrays for solve_ivp, and visualize temperature with contour plots over time.
Explore the three-body problem with sun, earth, and moon, derive coupled differential equations from Newton's gravitation, and solve them numerically to predict orbital motions and plan a Moon orbit.
Program the sun-earth-moon three-body differential equations in python, define position and velocity vectors, compute inter-body distances and accelerations with gravity G, and solve the 18-equation system from initial conditions.
Solve the sun-earth-moon three-body differential equations using solve_ivp with RK45, exploring time spans up to years, adjusting tolerances to improve trajectory accuracy and visualize orbits.
Analyze the sun-earth-moon three-body dynamics by solving 18 differential equations, revealing Earth's year-long orbit and the Moon's orbit around Earth, with visualization and tolerance-driven accuracy.
Explore how introducing a small z component for the Moon creates a realistic inclination in the Sun-Earth-Moon system, moving from two- to three-dimensional plots and highlighting the three-body problem.
Add a lightweight spaceship as a fourth body to the Sun–Earth–Moon system and model its gravity-driven orbit in Python. Visualize the trajectory alongside Earth and Moon.
Explore how increasing the spaceship's starting velocity creates an elliptical orbit around Earth, analyze trajectory distance and velocity changes, and assess interactions with the Moon and potential Earth escape.
Simulate Earth escape by increasing orbital velocity to produce elliptical and Sun-dominated trajectories, showing a spacecraft leaving Earth and orbiting the Sun before potential re-entry near Earth after years.
Vary starting velocity to observe transitions from circular to elliptical orbits and possible Moon encounters. Show how close Moon flybys enable slingshot maneuvers to escape Earth and reach Moon orbit.
Plan a brake maneuver to enter a Moon orbit by firing thrust opposite to the spacecraft’s velocity, modeled with a heavy-side function for engine on/off in a four-body IVP.
Finish the differential equations section and explore chaotic solutions, the butterfly effect, the heat equation, the Lawrence system, with interacting parts and spacecraft trajectories to the Moon.
Apply concepts from derivatives, integrals, matrix eigenvalues, and Fourier transforms to analyze coupled harmonic oscillators, such as pendulums, revealing characteristic frequencies and how interactions alter motion.
Explore the eigenvalue problem for three coupled oscillators by deriving their equations of motion, transforming to deviations from equilibrium, and casting the system into a matrix for numerical eigenvalue analysis.
Numerically solve two coupled differential equations using a first-order formulation with solve_ivp RK45. Explore the matrix eigenvalues and transform back to original coordinates to reveal non-harmonic, potentially unstable dynamics.
Explore why three coupled oscillators form an eigenvalue problem. Apply a unitary transformation to diagonalize the system, solve for eigenvalues, and relate them to frequencies via sqrt(K/m * lambda).
Write a Python routine to compute eigenvalues by solving det(A - lambda I) = 0 for a given matrix, and interpret the resulting eigenfrequencies.
Implement eigenvalue calculation by coding a 3×3 determinant, form the characteristic polynomial, and build a sign-change based root finder to locate all eigenvalues.
Analyze eigenvalues and eigenfrequencies of three coupled oscillators, identify eigenvectors and modes, and show how the numerical solution becomes a sum of three sine functions via Fourier analysis and fitting.
An update corrects the eigenvectors for a symmetric oscillator system, showing the first eigenvector has outer oscillators moving together. Center of mass is conserved in the middle mode.
Use the Fourier transform to extract characteristic frequencies from the numerical solution and locate peaks that match the system’s eigenfrequencies.
fit the numerical solution as a sum of three harmonic functions at frequencies omega1, omega2, and omega3, with three amplitudes and three phases, and minimize the error using gradient descent.
This lecture fits a numerical solution with a superposition of three cosine functions for three harmonic oscillators, optimizing amplitudes and phases via gradient descent and validating against eigenfrequencies.
Generalize the coupled oscillator model to n oscillators, solve the eigenvalue problem for frequencies, build harmonic functions, and verify numerically with the Fourier transform.
Transform a straight line of coupled oscillators into a ring using periodic boundary conditions, yielding a circular one-dimensional system with modified end couplings and a zero-frequency translation mode.
Explore Monte Carlo simulations to solve complex physics problems, replacing gradient descent with random parameter updates. Learn by approximating pi with random points and simulating a three-dimensional magnet's collective behavior.
Use a Monte Carlo approach to approximate pi by generating random points in a square, counting those inside a circle, and computing pi as four times the inside-to-total ratio.
Estimate pi using a Monte Carlo approach by sampling points in a square and counting how many fall inside the circle; pi approx equals four times inside divided by total.
Compare two Monte Carlo methods to approximate pi using random points: an array-based approach and a loop, highlighting faster vectorized code and pi from the area ratio.
Demonstrates setting up a grid of magnetic moments with fixed length, then uses a Monte Carlo metropolis algorithm and Metropolis steps to minimize energy via random reorientation and acceptance criteria.
Define exchange energy for a ferromagnetic system using the Heisenberg nearest-neighbor interaction with periodic boundary conditions. Apply a Monte Carlo Metropolis step to minimize energy and explore magnetic moment configurations.
Perform the metropolis step of the Monte Carlo algorithm by randomly selecting a magnetic moment. Rotate it randomly, compute energy old and energy new, and accept energy-decreasing changes updating magnetization.
Execute a Monte Carlo spin simulation with Metropolis steps to update magnetization and energy, track energy changes, and address convergence and local minima toward the global minimum.
Introduce finite-temperature updates that accept energy increases via a Boltzmann factor to escape local energy minima and converge toward a ferromagnetic state.
Introduce the zeeman energy term to model interaction with an external magnetic field and update the energy and metropolis step, revealing field-driven alignment of magnetic moments.
Explore how the Dzyaloshinskii–Moriya interaction generates non-collinear spin textures and how Monte Carlo simulations reveal spin spirals and the role of energy terms such as exchange and DMI.
Explore Monte Carlo methods to simulate the collective magnetic behavior of tiny magnets, balancing randomness with iteration tuning, noting downsides, and comparing to gradient descent.
Explore an introductory appetizer on quantum mechanics and solving the shooting equation, highlighting numerical solutions with Python and guiding learners to the related course for deeper theory.
Use the shooting method to solve the stationary Schrödinger equation for a particle in a box with Python and NumPy, finding the first eigenvalue and eigenfunction by energy scans.
Explore the eigensystem of a particle in a box by using a shooting method to scan energy, locate wavefunction zeros, and obtain and plot eigenvalues and eigenfunctions.
Explore adapting the notebook to the harmonic oscillator potential, solving for energy eigenvalues and eigenfunctions numerically, and handling propagation and boundary conditions.
Numerically determine the eigensystem of the quantum harmonic oscillator using stabilized shooting methods and energy-dependent boundaries to obtain eigenvalues and eigenfunctions, then compare quantum and classical probability distributions.
Apply the shooting method to solve stationary equations and understand instability caused by simple derivative calculations. Use Mathematica’s eigen system to compute harmonic oscillator eigenvalues and eigenfunctions.
Demonstrate solving the wave function and energy simultaneously through differential equations in quantum mechanics, highlighting a slightly different teaching style within this section.
This course is for everyone who wants to learn and get better in Python and physics.
Except for some school mathematics, no prior knowledge is required. We will start from the basics and climb the ladder up to advanced projects!
Python is an enormously powerful tool and widely used in theoretical and computational physics.
It is not difficult to use but the whole topic can be overwhelming to learn if you are on your own.
In computational physics we use numerical techniques from mathematics, such as:
Interpolation & Model fitting
Derivatives & Integrals
Differential equations
Eigenvalue problems
Monte Carlo methods
to solve problems from all areas of physics.
You are kindly invited to join this carefully prepared course that will teach you all you need to know about Python for scientific programming. It includes a crash course, quizzes, exercises, solutions and, of course, hands-on programming sessions in which we will solve real-life examples, such as
Calculating the magnetic field of a charged wire (integrals & derivatives)
Chaos & the butterfly effect (differential equations)
Heat propagation in a sample (differential equations)
Simulating (and navigating) a spaceship interacting with sun, earth and moon (differential equations)
The strange behavior of coupled oscillators (Eigenvalue problems, Fourier analysis & fitting procedure)
Ferromagnets & Antiferromagnets (Monte Carlo methods)
Special properties of graphene (Advanced science lecture about the Nobel prize winning material)
... & many more
Why me?
My name is Börge Göbel and I am a postdoc working as a scientist in theoretical physics.
I have refined my advisor skills as a tutor of Bachelor, Master and PhD students in theoretical physics and have other successful courses here on Udemy.
Especially when I started my PhD, I was impressed how easily you can solve demanding tasks with Python. I have used the program for the results in many of my publications and have recommended Python to all of my students.
“Excellent course, it is just what I was looking for: everything you need to know about Python for solving physics problems from the basics. Very well structured, full of examples and applications to real problems, template files to help you follow the classes and entertaining while instructive explanations.“ - Adrián Terrones Aragón
I hope you are excited and I kindly welcome you to our course!