@woosh/meep-engine
Version:
Pure JavaScript game engine. Fully featured and production ready.
68 lines (48 loc) • 1.82 kB
JavaScript
import { assert } from "../assert.js";
import { EPSILON } from "./EPSILON.js";
/**
* Return solutions for a quadratic polynomial: ax² + bx + c
* Typically there will be 2 solution, in some cases we will have 0, having 1 solution is impossible
* This solver only deals with real numbers, so imaginary solution are not provided. In case solution would be imaginary - we return 0 roots
* @param {number} a
* @param {number} b
* @param {number} c
* @param {number[]} result solutions are written here
* @param {number} result_offset offset into result array where solutions are written to
* @returns {number} number of found solutions (roots)
*/
export function solveQuadratic(
result, result_offset,
a, b, c
) {
assert.isNumber(a, 'a');
assert.isNumber(b, 'b');
assert.isNumber(c, 'c');
if (Math.abs(a) < EPSILON) {
if (Math.abs(b) < EPSILON) {
if (Math.abs(c) < EPSILON) {
// special case, all variables are close to 0
result[result_offset] = 0;
result[result_offset + 1] = 0;
return 2;
}
} else {
result[result_offset] = -c / b;
result[result_offset + 1] = -c / b;
return 2;
}
} else {
// 2 root solution
const disc_sqr = b * b - 4 * a * c;
if (disc_sqr >= 0) {
// if discriminant square is negative, solution can only be imaginary, we don't deal with that
const disc = Math.sqrt(disc_sqr);
const a2 = 2 * a;
result[result_offset] = (-b - disc) / a2;
result[result_offset + 1] = (-b + disc) / a2;
return 2;
}
}
// no roots
return 0;
}