commonsmachinery / blockhash-js

Image perceptual hash calculation in javascript
http://blockhash.io/
MIT License
172 stars 49 forks source link

Incorrect calculation of median #11

Closed kseo closed 6 years ago

kseo commented 8 years ago

median([1,2,3,4]) should return 2.5, but the current implementation mistakenly returns 3.5 due to a bug in index calculation:

var median = function(data) {
    var mdarr = data.slice(0);
    mdarr.sort(function(a, b) { return a-b; });
    if (mdarr.length % 2 === 0) {
        return (mdarr[mdarr.length/2] + mdarr[mdarr.length/2 + 1]) / 2.0;
    }
    return mdarr[Math.floor(mdarr.length/2)];
};

should be

var median = function(data) {
    var mdarr = data.slice(0);
    mdarr.sort(function(a, b) { return a-b; });
    if (mdarr.length % 2 === 0) {
        return (mdarr[mdarr.length/2 - 1] + mdarr[mdarr.length/2]) / 2.0;
    }
    return mdarr[Math.floor(mdarr.length/2)];
};
mzeinstra commented 8 years ago

Thanks kseo,

I know that the developers behind this tool are currently all on a holiday and will most likely pick this up as soon as they are back.

In the meantime, I'm curious how are you using blockhash? In what kind of projects?

kseo commented 8 years ago

@mzeinstra I ported blockhash to Haskell (https://hackage.haskell.org/package/blockhash) for my personal project.

klokan commented 8 years ago

The same code is in python as well: https://github.com/commonsmachinery/blockhash-python/blob/master/blockhash.py#L13

artfwo commented 6 years ago

Fixed in master, sorry about forgetting this stupid mistake. @kseo Could you update the haskell package as well?