Math → Kotlin Cheatsheet
This is still very much a work-in-progress and I welcome any contributions. This cheat sheet was inspired by Jam3's Math as Code project.
I am using this online LaTeX equation editor to generate expressions, and if you want to learn MathJax notation here is a great resource.
While you are here, please rally this issue on Dokka to bring MathJax support to Kotlin Docs.
Summation
This symbol indicates you are summing a series of items. It is probably one of the most commonly used symbols in math to express iterative addition.
Nested Summation
When you see more than one summation, this means they are nested summations. This is no different than summing with nested loops or flatmapped functional sequences.
(1..4).flatMap { i -> (4..20).map { j -> 2 *i * j } }.sum()
Variables
Hopefully the concept of a variable (such as x
) should be self-explanatory to a programmer. However, in mathematical notation it is common for subscripts to distinctly describe several instances of that variable. For instance, we can use old
and new
x
values to measure a rate of change.
Here is a more iterative example. We can define 5 different variables all named , but notate them as . Here is how we can notate an average operation.
val xValues = listOf(23, 65, 45, 23, 66)
val xAverage = allXs.sum() / 5
// or
val xAverage = allXs.average()
Mathematics and programming are similar in that they try to generalize. Instead of formulating an average for just 5
variables, we can notate it for any n
number of variables.
To maximize fanciness, we can go a step further and use a summation operator and just generalize each x
value as . Note that n
is the number of variables/elements we are averaging.
Naming Subscripted Variables in Kotlin
Trying to express subscripted variables like and can be a little awkward in code. In Kotlin, you can choose to stick with conventional camelCase or break style guidelines by using underscores.
val x1 = 12
val x_1 = 12
val xOld = 13
val x_old = 13
Hopefully you will not run into this decision often, as you may express variables as iterated elements in collections/sequences rather than give each one an explicit variable name.
Elements and Sets
Functions
Math Expression | Description | Kotlin Code |
---|---|---|
Exponent of e |
exp(x) |
|
Natural logarithm | ln(x) |