Category talk:Wren-math: Difference between revisions

→‎Source code: Added some convenience methods to the Int and Nums classes.
(→‎Source code: Added methods to calculate gcd and lcm of a list of integers.)
(→‎Source code: Added some convenience methods to the Int and Nums classes.)
Line 94:
/* Int contains various routines which are only applicable to integers. */
class Int {
// Truncated integer division (consistent with % operator).
static quo(x, y) { (x/y).truncate }
 
// Floored integer division (consistent with 'mod' method below).
static div(x, y) { (x/y).floor }
 
// Floored integer division modulus.
static mod(x, y) { ((x % y) + y) % y }
 
// Returns whether or not 'n' is a perfect square.
static isSquare(n) {
Line 471 ⟶ 480:
static max(a) { a.reduce { |acc, x| (x > acc) ? x : acc } }
static min(a) { a.reduce { |acc, x| (x < acc) ? x : acc } }
 
// As above methods but applying a function 'f' to each element of 'a'
// before performing the operation.
// 'f' should take a single Num parameter and return a Num.
static sum(a, f) { a.reduce(0) { |acc, x| acc + f.call(x) } }
static mean(a, f) { sum(a, f)/a.count }
static geometricMean(a, f) { a.reduce { |prod, x| prod * f.call(x)}.pow(1/a.count) }
static harmonicMean(a, f) { a.count / a.reduce { |acc, x| acc + 1/f.call(x) } }
static quadraticMean(a, f) { (a.reduce(0) { |acc, x| acc + f.call(x).pow(2) }/a.count).sqrt }
static prod(a, f) { a.reduce(1) { |acc, x| acc * f.call(x) } }
static max(a, f) { a.reduce { |acc, x|
var fx = f.call(x)
return (fx > acc) ? fx : acc
} }
static min(a, f) { a.reduce { |acc, x|
var fx = f.call(x)
return (fx < acc) ? fx : acc
} }
 
// Returns the median of a sorted list 'a'.
9,485

edits