Numerical integration: Difference between revisions
Content added Content deleted
(Added Kotlin) |
|||
Line 2,612: | Line 2,612: | ||
simpson(x -> x, 0, 6000, 6000000) |
simpson(x -> x, 0, 6000, 6000000) |
||
(0.25000000000000006,4.605170384957135,1.25e7,1.8e7) |
(0.25000000000000006,4.605170384957135,1.25e7,1.8e7) |
||
</pre> |
|||
=={{header|Kotlin}}== |
|||
<lang scala>// version 1.1.1 |
|||
typealias Func = (Double) -> Double |
|||
fun integrate(a: Double, b: Double, n: Int, f: Func) { |
|||
val h = (b - a) / n |
|||
val sum = DoubleArray(5) |
|||
for (i in 0 until n) { |
|||
val x = a + i * h |
|||
sum[0] += f(x) |
|||
sum[1] += f(x + h / 2.0) |
|||
sum[2] += f(x + h) |
|||
sum[3] += (f(x) + f(x + h)) / 2.0 |
|||
sum[4] += (f(x) + 4.0 * f(x + h / 2.0) + f(x + h)) / 6.0 |
|||
} |
|||
val methods = listOf("LeftRect ", "MidRect ", "RightRect", "Trapezium", "Simpson ") |
|||
for (i in 0..4) println("${methods[i]} = ${"%f".format(sum[i] * h)}") |
|||
println() |
|||
} |
|||
fun main(args: Array<String>) { |
|||
integrate(0.0, 1.0, 100) { it * it * it } |
|||
integrate(1.0, 100.0, 1_000) { 1.0 / it } |
|||
integrate(0.0, 5000.0, 5_000_000) { it } |
|||
integrate(0.0, 6000.0, 6_000_000) { it } |
|||
}</lang> |
|||
{{out}} |
|||
<pre> |
|||
LeftRect = 0.245025 |
|||
MidRect = 0.249988 |
|||
RightRect = 0.255025 |
|||
Trapezium = 0.250025 |
|||
Simpson = 0.250000 |
|||
LeftRect = 4.654991 |
|||
MidRect = 4.604763 |
|||
RightRect = 4.556981 |
|||
Trapezium = 4.605986 |
|||
Simpson = 4.605170 |
|||
LeftRect = 12499997.500000 |
|||
MidRect = 12500000.000000 |
|||
RightRect = 12500002.500000 |
|||
Trapezium = 12500000.000000 |
|||
Simpson = 12500000.000000 |
|||
LeftRect = 17999997.000000 |
|||
MidRect = 18000000.000000 |
|||
RightRect = 18000003.000000 |
|||
Trapezium = 18000000.000000 |
|||
Simpson = 18000000.000000 |
|||
</pre> |
</pre> |
||