A thermostat is the simplest closed-loop controller: it reads the temperature and decides whether the boiler runs. A thermostat that switches on below the setpoint and off above it would click on and off with every tiny wobble of the reading, wearing out the boiler. Real thermostats use hysteresis: a gap of band °C on each side of the setpoint where they keep doing whatever they were already doing.
The boiler starts off. For each reading, in order:
- if the boiler is off and the reading is below
setpoint - band, it switches on; - if the boiler is on and the reading is above
setpoint + band, it switches off; - otherwise it stays as it is.
Write thermostat_log(readings, setpoint, band) that returns a tuple (switches, on_readings): how many times the boiler switched (on or off), and for how many readings it was on after that reading's decision.
Examples
Input: readings = [19.0, 18.4, 18.9, 19.6, 20.6, 20.2, 19.4, 18.3], setpoint = 19.5, band = 0.5
Output: (3, 4)
Explanation: the thresholds are 19.0 and 20.0. 19.0 is not below 19.0, so the boiler stays off;
18.4 switches it on, and it stays on through 18.9 and 19.6; 20.6 switches it off; it stays off
through 20.2 and 19.4; 18.3 switches it on again. Three switches; on after readings 2, 3, 4 and 8.
Input: readings = [21.0, 22.0], setpoint = 20, band = 0
Output: (0, 0)
Constraints
band >= 0; withband = 0the thermostat has no hysteresis at all
Goals
- Turn a measurement into an on/off decision
- Use two thresholds and the current state to decide (hysteresis)
- Count how often an actuator switches