--- title: Euler method id: 59880443fb36441083c6c20e challengeType: 5 forumTopicId: 302258 --- ## Description
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: with an initial value To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation: then solve for $y(t+h)$: which is the same as The iterative solution rule is then: where $h$ is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand. Example: Newton's Cooling Law Newton's cooling law describes how an object of initial temperature $T(t_0) = T_0$ cools down in an environment of temperature $T_R$: or It says that the cooling rate $\frac{dT(t)}{dt}$ of the object is proportional to the current temperature difference $\Delta T = (T(t) - T_R)$ to the surrounding environment. The analytical solution, which we will compare to the numerical approximation, is
## Instructions
Implement a routine of Euler's method and then use it to solve the given example of Newton's cooling law for three different step sizes of: and compare with the analytical solution. Initial values: First parameter to the function is initial time, second parameter is initial temperature, third parameter is elapsed time and fourth parameter is step size.
## Tests
```yml tests: - text: eulersMethod should be a function. testString: assert(typeof eulersMethod === 'function'); - text: eulersMethod(0, 100, 100, 2) should return a number. testString: assert(typeof eulersMethod(0, 100, 100, 2) === 'number'); - text: eulersMethod(0, 100, 100, 2) should return 20.0424631833732. testString: assert.equal(eulersMethod(0, 100, 100, 2), 20.0424631833732); - text: eulersMethod(0, 100, 100, 5) should return 20.01449963666907. testString: assert.equal(eulersMethod(0, 100, 100, 5), 20.01449963666907); - text: eulersMethod(0, 100, 100, 10) should return 20.000472392. testString: assert.equal(eulersMethod(0, 100, 100, 10), 20.000472392); ```
## Challenge Seed
```js function eulersMethod(x1, y1, x2, h) { } ```
## Solution
```js function eulersMethod(x1, y1, x2, h) { let x = x1; let y = y1; while ((x < x2 && x1 < x2) || (x > x2 && x1 > x2)) { y += h * (-0.07 * (y - 20)); x += h; } return y; } ```