This repository has been archived on 2022-10-20. You can view files and clone it, but cannot push or open issues or pull requests.
Math/horner.ts

49 lines
1.1 KiB
TypeScript

export class Horner {
constants: number[];
constructor(constants: number[]) {
this.constants = constants;
}
candidates() {
let max = Math.abs(this.constants[this.constants.length - 1]);
let min = 1;
let candidates: number[] = [];
for(let i = min; i<=max; i++) {
if(max % i == 0) {
candidates.push(i); candidates.push(-i);
}
}
return candidates;
}
functional_value(number: number) {
let new_polynom = [this.constants[0]];
for(let i=1; i<this.constants.length; i++) {
new_polynom.push(this.constants[i] + (new_polynom[new_polynom.length - 1] * number));
}
return new_polynom;
}
functional_value_0(): [number[], number] | void {
let c = this.candidates();
for(let i=0; i<c.length; i++) {
let new_polynom = this.functional_value(c[i]);
if(new_polynom[new_polynom.length - 1] == 0) return [new_polynom, c[i]];
}
}
static roots(horner: Horner) {
let roots: number[] = [];
while(true) {
let r = horner.functional_value_0();
if(!r) return [roots, horner.constants];
let [new_polynom, root] = r;
roots.push(root);
new_polynom.pop();
horner = new Horner(new_polynom);
}
}
}