Created
October 17, 2021 19:43
-
-
Save peheje/50568e85951dbd13fd0c092ac2c076aa to your computer and use it in GitHub Desktop.
Numerical integration with Kotlin and some lambda passing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main() { | |
} | |
// f is the function being integration, x is at which point, h is the size of each iteration along the x-axis | |
typealias Function = (x: Double) -> Double | |
typealias Rule = (f: Function, x: Double, h: Double) -> Double | |
fun leftRectangle(f: Function, x: Double, h: Double) = f(x) | |
fun midRectangle(f: Function, x: Double, h: Double) = f(x + h / 2.0) | |
fun rightRectangle(f: Function, x: Double, h: Double) = f(x + h) | |
fun trapezium(f: Function, x: Double, h: Double) = (f(x) + f(x + h)) / 2.0 | |
fun simpson(f: Function, x: Double, h: Double) = (f(x) + 4.0 * f(x + h / 2.0) + f(x + h)) / 6.0 | |
fun integral( | |
from: Double, | |
to: Double, | |
columns: Int, | |
rule: Rule, | |
f: (Double) -> Double | |
): Double { | |
val h = (to - from) / columns | |
var sum = 0.0 | |
for (i in 0 until columns) { | |
val x = from + i * h | |
sum += rule(f, x, h) | |
} | |
val integral = sum * h | |
println(integral) | |
return integral | |
} | |
// TESTS | |
import org.junit.jupiter.api.Assertions.* | |
import org.junit.jupiter.api.Test | |
import kotlin.math.ln | |
import org.junit.jupiter.api.Assertions.assertEquals as equals | |
internal class MainKtTest { | |
private val n = 10000 | |
private val delta = 0.01 | |
@Test | |
fun integralShould() { | |
val methods = mapOf( | |
"LeftRectangle" to ::leftRectangle, | |
"MidRectangle" to ::midRectangle, | |
"RightRectangle" to ::rightRectangle, | |
"Trapezium" to ::trapezium, | |
"Simpson" to ::simpson | |
) | |
for ((name, method) in methods) { | |
println(name) | |
val powerOfTwo: (Double) -> Double = { it * it } | |
equals(1.0 / 3.0, integral(0.0, 1.0, n, method, powerOfTwo), delta) | |
equals(8.0 / 3.0, integral(0.0, 2.0, n, method, powerOfTwo), delta) | |
equals(9.0, integral(0.0, 3.0, n, method, powerOfTwo), delta) | |
val oneOver: (Double) -> Double = { 1.0 / it } | |
equals(ln(100.0), integral(1.0, 100.0, n, method, oneOver), delta) | |
equals(ln(20.0 / 3.0), integral(6.0, 40.0, n, method, oneOver), delta) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment