Diffusion is the concept that explains how a drop of food coloring spreads in a glass of water, how a room fills up with the smell of perfume, or how heat conducts through a material. It is the process by which something spreads out evenly in a space where it was not previously evenly distributed. It is also used in things like fluid simulations. Diffusion is defined using derivatives and can appear very complicated when expressed in equations. However, it can be approximated with a simple calculation that compares neighboring values.


Simulate diffusion


Imagine a metal wire that has the highest temperature at its center and the lowest at both ends. Heat conducts from areas of high to low temperature, and we will observe how the temperature spreads over time. We will sample multiple points that are evenly distributed along the wire. The demo below illustrates the temperature changes at each point. The x-axis represents position, and the y-axis represents temperature (Note that y-axis is not position. The wire can have any shape, whether straight or bent).



The temperature change at a given point depends on the temperatures of its neighboring points. If the neighbors are hotter, the temperature will increase; if they are colder, the temperature will decrease. The rate of change is proportional to the temperature difference. If we call the temperature of the $i$-th point $u_i$, then the influence of the point to the left is proportional to$u_{i-1} - u_i$ and the influence of the point is proportional to $u_{i+1} - u_i$.

ある点の温度変化は、その周辺の点の温度に依存します。周辺の点がより熱い場合、温度は上昇します。逆に、周辺の点がより冷たい場合、温度は下降します。変化率は温度差に比例します。$i$番目の点の温度を$u_i$とすると、左側の点の影響は $u_{i-1} - u_i$ に比例し、右側の点の影響は $u_{i+1} - u_i$ に比例します。

Based on this idea, we can write a code to update the $u$ for the next moment in time (frame) as follows:


u_new[i] = u[i] + alpha / (dx * dx) * (u[i+1] - 2*u[i] + u[i-1]);

// (u[i + 1] - u[i]) + (u[i-1] - u[i]) = (u[i+1] - 2*u[i] + u[i-1])

The constant alpha depends on the material's properties, while dx represents the distance between points. It takes into account the fact that the greater the distance, the more effort is required to conduct the same amount of heat.

定数 alpha は素材の特性に依存し、 dx は点の間の距離を表します。距離が大きいほど同じ量の熱を伝えるために必要な労力が増えることを表現しています。