Category talk:Wren-math: Difference between revisions

Added evalPoly and diffPoly methods to Math class.
(→‎Source code: Added Math.nextPower method)
(Added evalPoly and diffPoly methods to Math class.)
Line 80:
}
return [pow, count]
}
 
// Returns the value of a polynomial when the variable is 'x' using Horner's method.
// Polynomials are represented by an ordered list of coefficients
// from the term with the highest degree down to the constant term.
static evalPoly(coefs, x) {
if (!(coefs is List) || coefs.count == 0 || !(coefs[0] is Num)) {
Fiber.abort("coefs must be a non-empty ordered list of numbers.")
}
if (!(x is Num)) Fiber.abort("x must be a number.")
var c = coefs.count
if (c == 1) return coefs[0]
var sum = coefs[0]
for (i in 1...c) sum = sum * x + coefs[i]
return sum
}
 
// Returns the coefficients of a polynomial following differentiation.
// Polynomials are represented as described in 'evalPoly' above.
static diffPoly(coefs) {
if (!(coefs is List) || coefs.count == 0 || !(coefs[0] is Num)) {
Fiber.abort("coefs must be a non-empty ordered list of numbers.")
}
var c = coefs.count - 1
if (c == 0) return [0]
var deriv = List.filled(c, 0)
for (i in 0...c) deriv[i] = (c - i) * coefs[i]
return deriv
}
 
9,477

edits