Category talk:Wren-math: Difference between revisions

Content added Content deleted
(Added evalPoly and diffPoly methods to Math class.)
(→‎Source code: Added various integer root functions..)
Line 153: Line 153:
static mod(x, y) { ((x % y) + y) % y }
static mod(x, y) { ((x % y) + y) % y }


// Returns whether or not 'n' is a perfect square.
// Returns the integer square root of 'x' or null if 'x' is negative.
static isSquare(n) {
static sqrt(x) { (x >= 0) ? x.sqrt.floor : null }
var s = n.sqrt.floor
return s * s == n
}


// Returns whether or not 'n' is a perfect cube.
// Returns the integer cube root of 'x'.
static isCube(n) {
static cbrt(x) { x.cbrt.truncate }

var c = n.cbrt.truncate
// Returns the integer 'n'th root of 'x' or null if 'x' is negative and 'n' is even.
return c * c * c == n
static root(n, x) {
if (!(n is Num) || !n.isInteger || n < 1) {
Fiber.abort("n must be a positive integer.")
}
return (n == 1) ? x :
(n == 2) ? sqrt(x) :
(n == 3) ? cbrt(x) :
(n % 2 == 1) ? x.sign * x.abs.pow(1/n).floor :
(n >= 0) ? x.pow(1/n).floor : null
}

// Returns whether or not 'x' is a perfect square.
static isSquare(x) {
var s = sqrt(x)
return s * s == x
}

// Returns whether or not 'x' is a perfect cube.
static isCube(x) {
var c = cbrt(x)
return c * c * c == x
}

// Returns whether or not 'x' is a perfect 'n'th power.
static isRoot(n, x) {
var r = root(n, x)
return r.pow(n) == x
}
}