Polyglot CheatSheet - Math
Last Updated: 2023-03-03
Sum of Array
JavaScript
Use .reduce()
:
> a = [1, 2, 3, 4]
[ 1, 2, 3, 4 ]
> a.reduce((x, y) => x + y)
10
The full signature is:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
However only total
and currentValue
are required.
Cumulative Sum
JavaScript
> const cumSum = [];
> [1, 2, 3, 4].reduce((a, b, i) => (cumSum[i] = a + b), 0);
> cumSum
[1, 3, 6, 10]
Max / Min / Mean
Go
Go has math.Max
to compare 2 numbers, but only for float
:
func Max(x, y float64) float64
Hack
Math\max()
Math\min()
Math\mean()
Round
Java
Integer.valueOf(Math.round(value));
Log
Java
These 2 are equivalent:
Math.log1p(x)
Math.log(x+1)
Fibonacci
Python
def fibonacci():
a, b = 0, 1
while True:
yield b
a, b = b, a + b