Example 1
Input: x0 = 5, k = 1, dt = 0.6, N = 3
Output: [5, 8.0, 12.8, 20.48]
Output: [5, 8.0, 12.8, 20.48]
The laws of nature are often written down in terms of differential equations. Everything from the motion of a football to the quantum state of a particle and the global ocean circulation are described in terms of differential equations!
Some differential equations can be solved by hand but many interesting ones cannot, so being able to compute numerical solutions is super useful. Here we'll solve a simple differential equation numerically.
We want to solve this differential equation describing exponential growth $$ \frac{dx}{dt} = kx $$ where $t$ is time, $k$ is a growth rate, and $x$ is the quantity we want to solve for (it could represent the number of bacteria in a petri dish or even compound interest). The differential equation is saying that the rate of change of $x$ is proportional to $x$ itself, so the more $x$ you have the faster $x$ will grow. We want to solve for $x(t)$ which will be a function of time $t$.
To solve the differential equation we will discretize it numerically so we can solve it iteratively. We will solve the equation at discrete times $t_0 = 0, t_1 = \Delta t, t_2 = 2\Delta t, \dots$, so the nth time step will be $t_n = n \Delta t$ where $\Delta t$ is a constant time step between solutions. Let's denote the current value of $x$ to be $x_n = x(n \Delta t)$. If we know $x_n$ then we want a formula for computing the next value $x_{n+1}$.
To find this formula, we start by discretizing the derivative $$ \frac{\Delta x}{\Delta t} = \frac{x_{n+1} - x_n}{\Delta t} = kx_n $$ where $\Delta x = x_{n+1} - x_n$ is the change in $x$ over the constant time step $\Delta t = t_{n+1} - t_n$. We can then solve for $x_{n+1}$ to get $$ x_{n+1} = x_n + k x_n \Delta t $$ So if we start with an initial value $x_0$ and we know the growth rate $k$ and time step $\Delta t$ then we can compute the solution $x_0, x_1, x_2, x_3, \dots$ which will be a numerical approximation to the real solution $x(t)$.
Input: Initial value $x_0$, growth rate $k$, time step $\Delta t$, and number of iterations $N$.
Output: The numerical solution $x_0, x_1, \dots, x_N$.
Difficulty | Timesink | ||
---|---|---|---|
Function | exponential_growth(x0, k, dt, n) |
You must be logged in to view your submissions.
Let us know what you think about this problem! Was it too hard? Difficult to understand? Also feel free to discuss the problem, ask questions, and post cool stuff on Discourse. You should be able see a discussion thread below. Would be nice if you don't post solutions in there but if you do then please organize and document your code well so others can learn from it.