From fc91cdd2dd8830b9c8af25c4f6aedfdf24b77c10 Mon Sep 17 00:00:00 2001 From: NunoSempere Date: Sat, 29 Jan 2022 17:45:23 -0500 Subject: [PATCH] fix: Make geom mean robust to low numbers by adding logs rather than multiplying small numbers. fix display of the number 1, which wasn't in any of the cases. --- lib/findPaths.js | 1 - lib/utils.js | 31 ++++++++++++++++++++++--------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/lib/findPaths.js b/lib/findPaths.js index cf33036..dcff28f 100644 --- a/lib/findPaths.js +++ b/lib/findPaths.js @@ -344,4 +344,3 @@ console.log(JSON.stringify(paths, null, 2)) let distances = findDistance({sourceElementId:2, targetElementId:4, links, nodes}) console.log(distances) */ - diff --git a/lib/utils.js b/lib/utils.js index b2647bb..53e8522 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -13,7 +13,8 @@ export const truncateValueForDisplay = (value) => { return Number(Math.round(value).toPrecision(2)); } else if (value > 1) { return Math.round(value * 10) / 10; - } else if (value < 1) { + } else if (value <= 1) { + return value; } }; export const _transformSliderValueToPracticalValue = (value) => @@ -37,15 +38,19 @@ export function numToAlphabeticalString(num) { } export function formatLargeOrSmall(num) { - if (num > 1) { - return toLocale(truncateValueForDisplay(num)); + let result; + if (num >= 1) { + result = toLocale(truncateValueForDisplay(num)); } else if (num > 0) { - return num.toFixed(-Math.floor(Math.log(num) / Math.log(10)) + 1); + result = num.toFixed(-Math.floor(Math.log(num) / Math.log(10)) + 1); } else if (num < -1) { - return num.toFixed(-Math.floor(Math.log(-num) / Math.log(10)) + 1); + result = num.toFixed(-Math.floor(Math.log(-num) / Math.log(10)) + 1); } else { - return toLocale(num); //return "~0" + result = toLocale(num); //return "~0" } + + console.log(`${num} -> ${result}`); + return result; } const firstFewMaxMergeSortSequence = [ 0, 0, 1, 3, 5, 8, 11, 14, 17, 21, 25, 29, 33, 37, 41, 45, 49, 54, 59, 64, 69, @@ -86,9 +91,17 @@ export function expectedNumMergeSortSteps(n) { } } -export const avg = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length; +const sum = (arr) => arr.reduce((a, b) => a + b, 0); -export const geomMean = (arr) => - arr.reduce((a, b) => a * b, 1) ^ (1 / arr.length); +export const avg = (arr) => sum(arr) / arr.length; + +export const geomMean = (arr) => { + let n = arr.length; + let logavg = sum(arr.map((x) => Math.log(x))); // works for low numbers much better + let result = Math.exp(logavg / n); + return result; +}; + +// export const geomMean = (arr) => arr.reduce((a, b) => a * b, 1); // ^ (1 / arr.length); // didn't work so well for low numbers. export const increasingList = (n) => Array.from(Array(n).keys());