-
Notifications
You must be signed in to change notification settings - Fork 1
Utility Module Reference
We just started working on documenting all of the utility functions. A great way to help out and become more familiar with the modules is to help us expand the documentation by editing the reference wiki. Feel free to adjust formatting, re-organize, whatever makes it easier for everyone to find the utility modules they need.
`cleanMath( expr )`Simplify formulas before display by removing, eg,
+ -
,- -
, and^1
That is, remove redundant + or - signs. For example: "3 + -2^1" would become "3 - 2"
rand( num )
Returns a random int in
[ 0, num ]
digits( n )
Returns an array of the digits of a nonnegative integer in reverse order
digits( 376 ) = [ 6, 7, 3 ]
integerToDigits( n )
Returns an array of the digits of a nonnegative integer. Returns an empty array if given a negative integer
integerToDigits( 376 ) = [ 3, 7, 6 ] integerToDigits( -376 ) = [ ]
decimalDigits( n )
Returns an array of the digits of a (positive or negative) decimal number in reverse order The location of the decimal is lost, as well as the sign
decimalDigits ( -3.456 ) = [ 6, 5, 4, 3 ]
decimalPlaces( n )
Returns the number of digits after the decimal place of a (positive or negative) number
decimalPlaces ( -3.456 ) = 3
digitsToInteger( digits )
Returns an integer from an array of the digits
digitsToInteger([ 6, 7, 3 ]) = 673
padDigitsToNum( digits, num )
Given an array of digits, returns a new one padded with enough 0's (at the end) to make the array of minimum length
num
. Note that if "num" is less than the length of the array, the array will return unchangedpadDigitsToNum([ 1, 2 ], 4) = [ 1, 2, 0, 0 ] padDigitsToNum([ 8, 7 ], 1) = [ 8, 7 ]
placesLeftOfDecimal
Returns exactly this array:
[ "one", "ten", "hundred", "thousand" ]
placesRightOfDecimal
Returns exactly this array:
[ "one", "tenth", "hundredth", "thousandth", "ten thousandth" ]
powerToPlace( power )
Returns the name of the place value as a string that corresponds to the given
power
of 10.Note that this function is limited to the data contained in
placesLeftOfDecimal
andplacesRightOfDecimal
So it will give an error if power is larger than 3 or smaller than -4.powerToPlace( 2 ) = "hundred" powerToPlace( -1 ) = "tenth"
roundTowardsZero( a )
Returns the number a with the decimal part truncated.
roundTowardsZero( 4.6 ) = 4 roundTowardsZero( -5.9 ) = -5 roundTowardsZero( 3.3 ) = 3
factorial
This function is supposed to be applied to a Natural number n and returns n! which is n * (n-1) * (n-2) * ... * 1 So for example: factorial(3) = 3! = 3 * 2 * 1 factorial(6) = 6! = 6 * 5* 4 * 3 * 2 * 1
getGCD( a, b )
Returns the greatest common divisor given two numbers, a and b.
getGCD(24,18) = 6
getLCM( a, b )
Returns lowest common multiple given two numbers, a and b.
getLCM(24,18) = 72
primes
Returns an array with all primes up to 100:
primes = [ 2, 3, 5, ... , 97]
getPrime()
Returns a random prime number < 100.
isPrime( n )
Checks if the given number n is prime for any natural number n.
isOdd( n )
Checks if the given number n is odd.
isOdd(24) = false
isEven( n )
Checks if the given number n is even.
isEven(24) = true
getOddComposite( min, max )
Returns a random odd composite number (that is not a prime number) between min and max. Default values are
min
= 0 andmax
= 100. Only returns numbers between 0 and 100, even ifmin
< 0 ormax
> 100.
getEvenComposite( min, max )
Returns a random even composite number between min and max. Default values are
min
= 0 andmax
= 100. Only returns numbers between 0 and 100, even ifmin
< 0 ormax
> 100.
getComposite()
Returns a random composite number between 0 and 100. Unlike
getEvenComposite()
andgetOddComposite()
,getComposite()
does not take any arguments.
getPrimeFactorization( x )
Returns an array of the prime factors of
x
.getPrimeFactorization( 54 ) = [2,3,3,3]
getFactors( number )
Gets all factors of the given number and returns them as an array in order.
getFactors( 12 ) = [1,2,3,4,6,12]
getNontrivialFactor( x )
Returns a random factor of x, but not 1 or x itself.
getMultiples( x, upperLimit)
Returns all the multiples of x that are less than or equal to upperLimit.
getMultiples(6,50) = [6, 12, 18, 24, 30, 36, 42, 48]
splitRadical( x )
Simplifies a radical down to it's simplest form by extracting the biggest possible factor from the radical. Returns an array of two integers, the first being the number outside the radical sign (the extracted factor), and the second being the number still left under the radical sign.
Since 12 = 2 * 2 * 3, the factor 2 can be extracted from the radical and:
splitRadical( 12 ) = [2,3]
splitCube( x )
Simplifies a cube radical down to it's simplest form by extracting the biggest possible factor from the radical. Returns an array of two integers, the first being the number outside the radical sign (the extracted factor), and the second being the number still left under the radical sign.
Since 54 = 27 * 2 and 3 is the cube radical of 27, the factor 3 can be extracted from the radical and:
splitCube( 54 ) = [2,3]
randRange( min, max, count1, count2 )
Gets a random integer between min and max, inclusive.
If a count1 is passed, it gives an 1 dimensional array(1 x count1) of random numbers in the min - max range.
If a count2 is passed, it gives an 2 dimensional array(count1 x count2) of random numbers in the min - max range.
randRangeUnique( min, max, count )
Returns an array (of size count) of unique (that is of mutually different) random numbers between min and max
randRangeUniqueNonZero( min, max, count )
Returns an array (of size count) of unique (that is of mutually different) random numbers between min and max, that are not zero
randRangeWeighted( min, max, target, perc )
Gets a random integer between min and max with a perc chance of hitting target (which is assumed to be in the range, but it doesn't have to be).
randRangeExclude( min, max, excludes )
Gets a random integer between min and max that is never any of the values in the excludes array.
randRangeWeightedExclude( min, max, target, perc, excludes )
Get a random integer between min and max with a perc chance of hitting target (which is assumed to be in the range, but it doesn't have to be). It never returns any of the values in the excludes array.
randRangeNonZero( min, max )
Similar to randRange except that zeroes are excluded.
randFromArray( arr, count )
Returns a random member of the given array. If a count is passed, it gives an array of random members of the given array.
randFromArrayExclude( arr, excludes )
Gets a random value from the given array that is not in the excludes array.
roundTo(place, value)
Rounds given value to specified integer place. Negative values round left of the decimal.
Example: roundTo(2, 123.456) returns 123.46
floorTo( precision, x )
Rounds x down to a number of decimal places specified by precision. If precision is negative, then x will be rounded down -precision places to the left of the decimal point.
floorTo(2, 10.989) = 10.98 floorTo(2, -10.989) = -10.99 floorTo(-1, 189.98) = 180
ceilTo( precision, x )
Works the same way as floorTo(), but rounds x up instead of down.
toFraction( decimal, tolerance )
Returns a fraction equivalent to a decimal in the form of an array of integers.
Tolerance
is optional and is set to 2^-46 by default.toFraction( 4/8 ) => [ 1, 2 ] toFraction( 0.666 ) => [ 333, 500 ] toFraction( 0.666, 0.001 ) => [ 2, 3 ]
shuffle( array, count )
Shuffles an array using a Fischer-Yates shuffle. If count is passed, returns an random sublist of that size.
sortNumbers( array )
Sorts numbers in an array.
truncate_to_max
restoreSign( x )
Returns 1 if x is positive, or -1 if x is negative.
isInt( x )
`negParens( n )`Returns true if x is an integer, or false if x is not an integer.
Wraps a number in parenthesis if it is negative.
decimalFraction
reduce( n, d )
Reduces fraction to simplest form. Returns result as an array( n, d ).
toFractionTex
fraction( n, d, defraction, reduce, small, parens )
Formats the latex of the fraction
n
/d
.
- Will use latex's
dfrac
unlesssmall
is specified as truthy.- Will wrap the fraction in parentheses if necessary (ie, unless the fraction reduces to a positive integer) if
parens
is specified as truthy.- Will reduce the fraction
n
/d
ifreduce
is specified as truthy.- Will defraction (spit out 0 if
n
is 0, spit outn
ifd
is 1, or spit outundefined
ifd
is 0) ifdefraction
is specified as truthy.
mixedFractionFromImproper( n, d, defraction, reduce, small, parens )
Formats the latex of the mixed fraction equivalent of the improper fraction
n/d
.
For flags
defraction
,reduce
,small
,parens
, see:mixedFraction()
mixedFraction( number, n, d, defraction, reduce, small, parens )
Formats the latex of the mixed fraction 'num n/d"
- For negative numbers, if it is a mixed fraction, make sure the whole number portion is negative. '-5, 2/3' should be 'mixedFraction(-5,2,3)'. Do not put negative for both whole number and numerator portion.
- Will use latex's
dfrac
unlesssmall
is specified as truthy.
- Will wrap the fraction in parentheses if necessary (ie, unless the fraction reduces to a positive integer) if
parens
is specified as truthy.
- Will reduce the fraction
n
/d
ifreduce
is specified as truthy.
- Will defract ( i.e. spit out 0 if
n
is 0, spit outn
ifd
is 1, or spit outundefined
ifd
is 0) ifdefraction
is specified as truthy.
fractionReduce( n, d, small, parens )
Calls fraction with the reduce and defraction flag enabled. Additional parameters correspond to the remaining fraction flags.
fractionSmall
piFraction( d )
Converts a decimal number,
d
, into the equivalent fraction of pi.piFraction( 1.57 ) = \frac{1}{2}\pi
reduces ( n, d )
Boolean returns true if the given fraction can be reduced.
fractionSimplification
mixedOrImproper
splitRadical( x )
Simplifies a radical down to it's simplest form. Returns an array of two integers, the first being the number outside the radical sign, and the second being the number inside the radical sign (same function as in math.js).
splitRadical( 12 ) = [2,3]
formattedSquareRootOf
squareRootCanSimplify
cardinal
Cardinal
quadraticRoots ( a, b, c )
Returns a string with the expression for the formatted roots of the quadratic equation with coefficients a, b, and c. Depends on expression.js for formatting.
"x = \pm 3"
commafy
plus
randVar
`plural( ... )`Returns a random algebraic variable (such as "x", or "y" ) to use in expressions.
Pluralization helper
Return “s” if NUMBER is not 1:
plural( NUMBER )
If necessary, magically pluralize and return “NUMBER word”:
plural( NUMBER, singular )
Return “NUMBER word”:
plural( NUMBER, singular, plural )
If necessary, magically pluralize and return “word”:
plural( singular, NUMBER )
Return “word”:
plural( singular, plural, NUMBER )
person( i )
Returns a person’s name from the shuffled list
personVar( i )
Returns the lower case first letter of the person’s name
he( i )
Returns “he” or “she”
He( i )
Returns “He” or “She”
him( i )
Returns “him” or “her”
his( i )
Returns “his” or “her”
His( i )
Returns “His” or “Her”
An( word )
Returns “A”, or “An” if
word
starts with a vowel
an( word )
Returns “a”, or “an” if
word
starts with a vowel
vehicle( i )
Returns a type of vehicle from the shuffled list
vehicleVar( i )
Returns the lower case first letter of the vehicle type
course( i )
Returns the name of a course (algebra, Spanish, etc.) from the shuffled list
courseVar( i )
Returns the lower case first letter of the course name
exam( i )
Returns a synonym for exam (test, quiz, etc.) from the shuffled list
binop( i )
Returns an unusual character symbol (diamond, circle, etc.) from the shuffled list.
item ( i )
Returns an item that can be grouped
see also:
group()
groupVerb()
group( i )
Returns the name of a group of items
see also:
item()
groupVerb()
groupVerb( i )
Returns the verb describing grouping a type of item
see also:
item()
group()
store( i )
Returns a type of store/shop
storeItem( i, j )
Returns an item that can be bought at a particular store
i
: which store in the shuffled listj
: which item in the shuffled listsee also: store
pizza( i )
Returns a round food item
exercise( i )
Returns a physical exercise
timeofday( i )
Returns a rough time of day (in the morning, at night, etc.)
school( i )
Returns the name of a school
clothing( i )
Returns an article of clothing
color( i )
Returns the name of a color
fruit( i )
Returns the name of a piece of fruit
deskItem( i )
Returns the name of an office supply
distance( i )
Returns a unit of distance (miles/kilometers)
rode( i )
Returns the past tense verb for an activity
see also:
ride()
bike()
biked()
biking()
ride( i )
Returns the infinitive verb for an activity
see also:
rode()
bike()
biked()
biking()
bike( i )
Returns the object noun for an activity
see also:
rode()
ride()
biked()
biking()
biked( i )
Returns a more specific past tense verb for an activity
see also:
rode()
ride()
bike()
biking()
biking( i )
Returns the present progressive tense verb for an activity
see also:
rode()
ride()
bike()
biked()
farmer( i )
Returns a type of farmer
see also:
crop()
field()
crop( i )
Returns the name of the crop grown by a farmer
see also:
farmer()
field()
field( i )
Returns the type of field used by a farmer
see also:
farmer()
crop()
side( i )
Returns “left” or “right”
shirtStyle( i )
Returns a style of shirt
trigFuncs
Array of trig basic trig functions. Currently includes sin, cos, and tan.
ddxTrigFuncs
Objects of functions to find the derivative of sin, cos, and tan respectively.
generateFunction( variable )
Generates a random differentiable expression object (function, derivative of the function, and incorrect derivatives)
Variable is what the function of differentiated with respect to. For example a variable of "x", would be the derivative with respect to x.
generateSpecialFunction( variable )
Similar to generateFunction, except with an emphasis on power rule, trig, and e^x / ln x derivatives.
ddxPolynomial( poly )
Finds the derivative of a polynomial. Poly is an instance of Polynomial object.
ddxPolynomialWrong1( poly )
Incorrectly finds the derivative of a polynomial by not decrementing exponents.
ddxPolynomialWrong2( poly )
Incorrectly finds the derivative of a polynomial by incrementing negative exponents.
ddxPolynomialWrong3( poly )
Incorrectly finds the derivative of a polynomial by reversing signs on all terms.
ddxPolynomialWrong4( poly )
Incorrectly finds the derivative of a polynomial by not multiplying coefficients.
ddxPolynomialWrong5( poly )
Incorrectly finds the derivative of a polynomial by flipping the signs on all terms.
Polynomial( minDegree, MaxDegree, coefs, variable, name)
`init( options )`Creates a new Polynomial object with a degree within the range ["minDegree", "MaxDegree"].
The "coefs" parameter is optional, but will assign the values given as coefficients.
The "variable" parameter will use the given symbol as the variable in the polynomial. (Tip: use
randVar()
to randomly select a variable.)The "name" parameter creates an easy reference for the polynomial when generating hints.
Initializes a graphie object with the specified range and scale
Args:
options
an object containing the following attributes:
range: a 2-d array (ie. [ [ xStart, xEnd ], [ yStart, yEnd] ] )
optional
scale: an array of two numbers [xScale, yScale]
scaleVector( point )
Simply multiplies the x and y values of the point by the xScale and yScale respectively
Args:
point
an array of two numbers
scalePoint( point )
Modifies the points to be positioned to scale
Args:
point
an array of two numbers
circle( center, radius [, style ] )
Draws a circle on a graphie canvas with a center at the specified point.
Args:
center
a point
radius
a number
style
optional style object
ellipse( center, radii [, style ] )
Draws a ellipse on a graphie canvas with a center at the specified point.
Args:
center
a point
radii
a point that is effectively the x radius and y radius
style
optional style object
arc( center, radius, startAngle, endAngle, sector [, style] )
Draws a partial circle
Args:
center
a point
radius
a number
startAngle
a number (degress)
endAngle
a number (degrees)
sector
a boolean - closes the arc by drawing lines from each endpoint of the arc to the center
style
optional style objectExample:
arc( [ 2, 1 ], 1, 0, 180, false, { style: BLUE } )
This creates an open, blue semicircle (top half of a circle).
path( points [, style ] )
Creates a path through each point specified in an array.
Args:
points
an array of points
style
optional style object
line( start, end [, style ] )
Args:
start
a point
end
a point
style
optional style object
grid( xRange, yRange [, style ] )
Args:
xRange
an array of two numbers (ie. [ xStart, xEnd ])
yRange
an array of two numbers (ie. [ yStart, yEnd ])
style
optional style object
label( location, text, [, position, latex, style ] )
Args:
location
a point at the center unless position is specified
text
a string
position
a string matching one of the following: center, above, above right, right, below right, below, below left, left, above left. The default is center.
latex
a boolean. The default is true.
style
optional style object (note: labels use color: and labelOpacity: attributes).
plotParametric( fn, range )
Takes a function of x that returns a point, and a range.
See alsoplot
plotPolar( fn, range )
Takes a function of x and maps it to polar coordinates.
fn
a function
range
a range
style
optional style object
plot
Draws the given function over the given range
Args:
fn
a function that takes an x value and returns a y value.
range
an array (ie. [ xStart, yStart ] )
style
optional style object
style( attrs [, fn ] )
Sets the drawing style
Args:
attrs
an object containing style attributes to change
fn
an optional function.If no function is supplied, the style changes will persist for this graphie object until they are explicitly changed again. If a function is supplied, the style changes will only apply to draw calls made inside the function.
sum( values )
Returns the sum of the items in values
mean( values )
Returns the average (sum divided by number of items) of values
median( values )
Returns the median (middle number) after sorting values
mode( values )
Returns the mode (most frequently occurring number) in values, or returns false if no such number exists.
variance( values )
Returns the SAMPLE variance of values. Use this function when values represents a sample of a larger population.
variancePop( values )
Returns the POPULATION variance of values. Use this function when values represents an entire population (i.e. every data point is included in values).
stdDev( values )
Returns the SAMPLE standard deviation of values.
stdDevPop( values )
Returns the POPULATION standard deviation of values.
randGaussian( tgtMean, tgtStdDev, count )
Returns an array of count random variables drawn from a normal distribution where mean = tgtMean and standard deviation = tgtStdDev. Defaults to a standard normal distribution (tgtMean = 0 & tgtStdDev = 1)
gaussianPDF( mean, stddev, x )
Returns the relative likelihood of x coming from a normal distribution where mean = mean and standard deviation = stddev. This likelihood is a number greater than zero and less than 1.
zScores( z )
Returns the probability of a z-score less than or equal to z. z is measured in hundredths and must be between 0 and 309.
zScores( 196 ) returns 0.975, because a z-score of 1.96 is greater than 0.975 of all possible z-scores.