JavaScript-QuickJS
view release on metacpan or search on metacpan
quickjs/qjscalc.js view on Meta::CPAN
return true;
return false;
}
Polynomial = function Polynomial(a)
{
if (new.target)
throw TypeError("not a constructor");
if (a instanceof Polynomial) {
return a;
} else if (Array.isArray(a)) {
if (a.length == 0)
a = [ 0 ];
Object.setPrototypeOf(a, Polynomial.prototype);
return a.trim();
} else if (polynomial_is_scalar(a)) {
a = [a];
Object.setPrototypeOf(a, Polynomial.prototype);
return a;
} else {
throw TypeError("invalid type");
}
}
function number_need_paren(c)
{
return !(Integer.isInteger(c) ||
Float.isFloat(c) ||
c instanceof Fraction ||
(c instanceof Complex && c.re == 0));
}
/* string for c*X^i */
function monomial_toString(c, i)
{
var str1;
if (i == 0) {
str1 = c.toString();
} else {
if (c == 1) {
str1 = "";
} else if (c == -1) {
str1 = "-";
} else {
if (number_need_paren(c)) {
str1 = "(" + c + ")";
} else {
str1 = String(c);
}
str1 += "*";
}
str1 += "X";
if (i != 1) {
str1 += "^" + i;
}
}
return str1;
}
/* find one complex root of 'p' starting from z at precision eps using
at most max_it iterations. Return null if could not find root. */
function poly_root_laguerre1(p, z, max_it)
{
var p1, p2, i, z0, z1, z2, d, t0, t1, d1, d2, e, el, zl;
d = p.deg();
if (d == 1) {
/* monomial case */
return -p[0] / p[1];
}
/* trivial zero */
if (p[0] == 0)
return 0.0;
p1 = p.deriv();
p2 = p1.deriv();
el = 0.0;
zl = 0.0;
for(i = 0; i < max_it; i++) {
z0 = p.apply(z);
if (z0 == 0)
return z; /* simple exit case */
/* Ward stopping criteria */
e = abs(z - zl);
// print("e", i, e);
if (i >= 2 && e >= el) {
if (abs(zl) < 1e-4) {
if (e < 1e-7)
return zl;
} else {
if (e < abs(zl) * 1e-3)
return zl;
}
}
el = e;
zl = z;
z1 = p1.apply(z);
z2 = p2.apply(z);
t0 = (d - 1) * z1;
t0 = t0 * t0;
t1 = d * (d - 1) * z0 * z2;
t0 = sqrt(t0 - t1);
d1 = z1 + t0;
d2 = z1 - t0;
if (norm2(d2) > norm2(d1))
d1 = d2;
if (d1 == 0)
return null;
z = z - d * z0 / d1;
}
return null;
}
function poly_roots(p)
{
var d, i, roots, j, z, eps;
var start_points = [ 0.1, -1.4, 1.7 ];
if (!(p instanceof Polynomial))
( run in 0.744 second using v1.01-cache-2.11-cpan-71847e10f99 )