Created
October 27, 2022 00:57
-
-
Save jlcarvalho/019e5fe0b07598ab8756124bb083c958 to your computer and use it in GitHub Desktop.
Calculates the overlapping area between normal distributions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import NormalDistribution from "normal-distribution"; | |
type TDistribution = Array<number>; | |
export function overlapArea(rating1: TDistribution, rating2: TDistribution) { | |
const [mean1, sd1] = rating1; | |
const [mean2, sd2] = rating2; | |
const normalDistribution1 = new NormalDistribution(mean1, sd1); | |
const normalDistribution2 = new NormalDistribution(mean2, sd2); | |
const min = Math.min(mean1 - 6 * sd1, mean2 - 6 * sd2); | |
const max = Math.max(mean1 + 6 * sd1, mean2 + 6 * sd2); | |
const range = max - min; | |
const resolution = range / Math.min(sd1, sd2); | |
const partwidth = range / resolution; | |
let intersectionArea = 0; | |
const begin = (Math.max(mean1 - 6 * sd1, mean2 - 6 * sd2) - min) / partwidth; | |
const end = (Math.min(mean1 + 6 * sd1, mean2 + 6 * sd2) - min) / partwidth; | |
/// Divide the range into N partitions | |
for (let ii = begin; ii < end; ii += 1) { | |
const partMin = partwidth * ii; | |
const partMax = partwidth * (ii + 1); | |
const areaOfDist1 = normalDistribution1.probabilityBetween( | |
partMin, | |
partMax | |
); | |
const areaOfDist2 = normalDistribution2.probabilityBetween( | |
partMin, | |
partMax | |
); | |
intersectionArea += Math.min(areaOfDist1, areaOfDist2); | |
} | |
return intersectionArea; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment