Skip to content

Instantly share code, notes, and snippets.

@kepocnhh
Created April 6, 2023 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kepocnhh/2914be8e2d29af0d4dca578e52a463a6 to your computer and use it in GitHub Desktop.
Save kepocnhh/2914be8e2d29af0d4dca578e52a463a6 to your computer and use it in GitHub Desktop.
// https://en.wikipedia.org/wiki/Geometric_series
/**
* @param a is coefficient
* @param r is the common ratio
* @return sum of a*r.pow(n) + a*r.pow(n - 1) + ... + a*r.pow(m - 1) + a*r.pow(m)
*/
fun getSumOfGeometricSeries(
a: Int = 1,
r: Double = 10.0,
m: Int = 0,
n: Int,
): Double {
require(m >= 0) { "m($m) is negative!" }
require(n >= m) { "n($n) < m($m)!" }
return r * a * (r.pow(m) - r.pow(n)) / (1.0 - r)
}
fun getSumOfGeometricSeries10(
a: Int = 1,
m: Int = 0,
n: Int,
): Double {
require(m >= 0) { "m($m) is negative!" }
require(n >= m) { "n($n) < m($m)!" }
return 10.0.pow(m + 1) * a * (1 - 10.0.pow(n - m)) / -9.0
}
/**
* @param a is coefficient
* @param r is the common ratio
* @param sum - value of a*r.pow(n) + a*r.pow(n - 1) + ... + a*r.pow(1)
* @return n
*/
fun getPowerOfGeometricSeries(
a: Int = 1,
r: Double = 10.0,
sum: Double
): Double {
return kotlin.math.log(1 - sum * (1.0 - r) / (a * r), r)
}
fun getPowerOfGeometricSeries10(
a: Int = 1,
sum: Double
): Double {
return kotlin.math.log10(1 + (sum * 9.0) / (a * 10.0))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment