DEV Community

Surendra Singh Kamboj
Surendra Singh Kamboj

Posted on AI-assisted

Newton's law of cooling in JavaScript: exact solution vs Euler's method

Newton's law of cooling says a hot object loses heat at a rate proportional to its temperature difference from the surroundings. It is a differential equation with a neat solution, and a good place to compare a numerical method with the exact answer. (I build PractiSci, which has a free Newton's law of cooling lab.)

The exact solution

dT/dt = −k (T − Tₛ) gives T(t) = Tₛ + (T₀ − Tₛ) e^(−kt).

const Ts = 25, T0 = 90, k = 0.03;       // °C, °C, per minute
const T = (t) => Ts + (T0 - Ts) * Math.exp(-k * t);
console.log(T(30).toFixed(2), T(60).toFixed(2)); // 51.43 35.74
Enter fullscreen mode Exit fullscreen mode

A cup at 90 °C in a 25 °C room is at 51.43 °C after 30 minutes and 35.74 °C after an hour. The time to reach 40 °C is ln((T₀ − Tₛ)/(40 − Tₛ)) / k:

console.log((Math.log((T0 - Ts) / (40 - Ts)) / k).toFixed(1)); // 48.9 minutes
Enter fullscreen mode Exit fullscreen mode

Euler's method against the exact answer

Step forward with T ← T − k(T − Tₛ)·dt and compare at 30 minutes.

for (const dt of [1, 0.01]) {
  let Te = T0;
  for (let t = 0; t < 30 - 1e-9; t += dt) Te += -k * (Te - Ts) * dt;
  console.log('dt', dt, Te.toFixed(2));
}
// dt 1    51.07
// dt 0.01 51.42
Enter fullscreen mode Exit fullscreen mode

With a 1 minute step the answer is 51.07, off by 0.36 °C. With a 0.01 minute step it is 51.42, within 0.01 °C of the exact 51.43. Smaller steps converge on the exact curve.

The half-life of the temperature difference

The gap to room temperature halves every ln 2 / k minutes. Here that is 23.1 minutes, no matter how hot the cup starts.

FAQ

Is the law exact?

It is a good approximation for small temperature differences (convection and conduction). For large differences, radiation matters and the decay is faster than exponential at the start.

What does k depend on?

The surface area, the material and how well the surroundings carry heat away. A cup with a lid has a smaller k.

Where can I try it?

The free Newton's law of cooling lab lets you change k and plot the cooling curve. More Class 11 labs are in the physics practicals.

Top comments (0)