Extract `uniformDistribution` (#274)
Test Plan: Unit tests added. Run `yarn test`. wchargin-branch: extract-uniformDistribution
This commit is contained in:
parent
017fbd774a
commit
69b9f6657d
|
@ -9,6 +9,7 @@ import type {
|
|||
Distribution,
|
||||
SparseMarkovChain,
|
||||
} from "../../core/attribution/markovChain";
|
||||
import {uniformDistribution} from "../../core/attribution/markovChain";
|
||||
|
||||
export type PagerankResult = AddressMap<{|
|
||||
+address: Address,
|
||||
|
@ -132,10 +133,6 @@ function sparseMarkovChainAction(
|
|||
return result;
|
||||
}
|
||||
|
||||
function uniformDistribution(n: number): Distribution {
|
||||
return new Float64Array(n).fill(1 / n);
|
||||
}
|
||||
|
||||
function findStationaryDistribution(chain: SparseMarkovChain): Distribution {
|
||||
let r0 = uniformDistribution(chain.length);
|
||||
function computeDelta(pi0, pi1) {
|
||||
|
|
|
@ -65,3 +65,10 @@ export function sparseMarkovChainFromTransitionMatrix(
|
|||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function uniformDistribution(n: number): Distribution {
|
||||
if (isNaN(n) || !isFinite(n) || n !== Math.floor(n) || n <= 0) {
|
||||
throw new Error("expected positive integer, but got: " + n);
|
||||
}
|
||||
return new Float64Array(n).fill(1 / n);
|
||||
}
|
||||
|
|
|
@ -1,6 +1,9 @@
|
|||
// @flow
|
||||
|
||||
import {sparseMarkovChainFromTransitionMatrix} from "./markovChain";
|
||||
import {
|
||||
sparseMarkovChainFromTransitionMatrix,
|
||||
uniformDistribution,
|
||||
} from "./markovChain";
|
||||
|
||||
describe("sparseMarkovChainFromTransitionMatrix", () => {
|
||||
it("works for a simple matrix", () => {
|
||||
|
@ -77,3 +80,19 @@ describe("sparseMarkovChainFromTransitionMatrix", () => {
|
|||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("uniformDistribution", () => {
|
||||
it("computes the uniform distribution with domain of size 1", () => {
|
||||
const pi = uniformDistribution(1);
|
||||
expect(pi).toEqual(new Float64Array([1]));
|
||||
});
|
||||
it("computes the uniform distribution with domain of size 4", () => {
|
||||
const pi = uniformDistribution(4);
|
||||
expect(pi).toEqual(new Float64Array([0.25, 0.25, 0.25, 0.25]));
|
||||
});
|
||||
[0, -1, Infinity, NaN, 3.5, '"beluga"', null, undefined].forEach((bad) => {
|
||||
it(`fails when given domain ${String(bad)}`, () => {
|
||||
expect(() => uniformDistribution((bad: any))).toThrow("positive integer");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue