Skip to content

Bug report: Median operation returns incorrect result for unsorted odd-length inputs #2239

@williballenthin

Description

@williballenthin

Describe the bug
The Median operation only sorts the input array when its length is even. For odd-length inputs it returns the middle element of the unsorted array, which is mathematically incorrect.

src/core/lib/Arithmetic.mjs, median() function, lines 84-93

export function median(data) {
    if ((data.length % 2) === 0 && data.length > 0) {
        data.sort(function(a, b) {
            return a.minus(b);
        });
        const first = data[Math.floor(data.length / 2)];
        const second = data[Math.floor(data.length / 2) - 1];
        return mean([first, second]);
    } else {
        return data[Math.floor(data.length / 2)];
    }
}

For odd-length arrays the function skips sorting entirely and returns data[Math.floor(data.length / 2)]. The median of any numeric set requires sorting first.

To Reproduce
add the Median operation with input 10,1,2 (comma delimiter). Expected output is 2 (the median of [1, 2, 10]); actual output is 1 (the middle element of the unsorted array).

Additional context
Suggested fix:

export function median(data) {
    if (data.length === 0) {
        return undefined;
    }

    data.sort(function(a, b) {
        return a.minus(b);
    });

    if ((data.length % 2) === 0) {
        const first = data[Math.floor(data.length / 2)];
        const second = data[Math.floor(data.length / 2) - 1];
        return mean([first, second]);
    }

    return data[Math.floor(data.length / 2)];
}

This sorts unconditionally, handles empty input by returning undefined, and preserves existing even-length behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions