Skip to content

Instantly share code, notes, and snippets.

@Robfz
Last active July 1, 2019 17:04
Show Gist options
  • Save Robfz/3cf5a23cddda3f35e75df148eeacfa08 to your computer and use it in GitHub Desktop.
Save Robfz/3cf5a23cddda3f35e75df148eeacfa08 to your computer and use it in GitHub Desktop.
CAT
const A = [41600];
const t = [0];
const B = [
4256.6,
4272.37,
4288.8,
4305.9,
4323.71,
4342.26,
4361.57,
4381.69,
4402.64,
4424.45,
4447.17,
4470.82
];
const s = [...Array(12).keys()].map((e, i) => (i + 1) / 12);
const calculateCAT = (
A: number[],
t: number[],
B: number[],
s: number[],
maxCAT = 1000,
): number => {
const resolution = 1000;
const tryCAT = (cat: number) => {
const firstTerm = A.reduce(
(acc, Aj, j) => acc + Aj / Math.pow(1 + cat, t[j]),
0
);
const secondTerm = B.reduce(
(acc, Bk, k) => acc + Bk / Math.pow(1 + cat, s[k]),
0
);
return Math.abs(firstTerm - secondTerm);
};
const calculateCATInternal = (low: number, up: number): number => {
const pivot = Math.ceil((low + up) / 2);
const pivotValue = tryCAT(pivot / resolution);
const left = tryCAT((pivot - 1) / resolution);
const right = tryCAT((pivot + 1) / resolution);
if (left > pivotValue && right > pivotValue) {
return pivot / resolution;
} else if (left < pivotValue) {
return calculateCATInternal(low, pivot);
} else {
return calculateCATInternal(pivot, up);
}
};
return calculateCATInternal(0, maxCAT * resolution);
};
console.log(calculateCAT(A, t, B, s));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment