Math

math

This project is used to showcase how to implement simple real time statistical operations in node-red.

List of used nodes

  • Inject/Timestamp – Triggers flow execution

  • Function – Adds custom logic using JavaScript

  • Debug – Displays messages in the debug console

For details, see Node-RED Documentation

GROUP: generate values

group generate values

This group is used to simulate a random value between 1 and 10 and store it in an array.

FLOW: create random measurement

This flow outputs an object inside the payload property of the msg object. The object contains a measurement value, an ID, and a timestamp.

The flow implements a circular buffer of size 1000. To persist the array, node context is used, which provides get and set methods. Node context is reset after each deployment but retains values between different inputs.

const valuesArr = context.get("valuesArr") ?? Array(1000).fill(0);
let count = context.get("count") ?? 0;

console.log("count: ", count);
console.log("values arr: ", valuesArr);

valuesArr[count % 1000] = msg.payload.value;
count++;

context.set("count", count);
context.set("valuesArr", valuesArr);

msg.payload = {
    count: count,
    valuesArr: valuesArr
}

return msg;

GROUP: simple operations

group simple operations

This group implements three simple operations: counting, calculating the sum, and finding the minimum and maximum values. For all three flows, node context is used to persist the memory of previous values. All values are calculated dynamically, meaning each time a new value arrives, a new result is calculated.

GROUP: statistical operations

group statistical operations

This group implements more complex operations. It uses the previously persisted circular buffer of size 1000.

FLOW: median

The buffer is sorted, and based on the array length, the middle index is selected. If the array length is divisible by 2, there is no single middle index, and the mean of the two middle values is calculated.

if (arrayLen % 2) {
    msg.payload = {
        median: fullArr[Math.floor(arrayLen / 2)]
    }
} else {
    const index = arrayLen / 2;
    msg.payload = {
        median: (fullArr[index] + fullArr[index - 1]) / 2
    }
}

FLOW: average, variance and standard deviation

The average of all non-zero values in the array is calculated and passed forward. The average is also used to compute the variance and standard deviation. The map method is used to apply the same operation to each array element.

const subsArr = fullArr.map(e => (e - avg) ** 2);
const variance = subsArr.reduce((sum, curr) => sum + curr, 0) / fullArr.length;

Variance is calculated as:

variance = Σ(x - mean)² / N

Standard deviation is:

std_deviation = √variance