RosettaCodeData/Task/Numerical-integration/Julia/numerical-integration.julia

17 lines
402 B
Text
Raw Permalink Normal View History

2018-06-22 20:57:24 +00:00
function simpson(f::Function, a::Number, b::Number, n::Integer)
h = (b - a) / n
s = f(a + h / 2)
2014-01-17 05:32:22 +00:00
for i in 1:(n-1)
2018-06-22 20:57:24 +00:00
s += f(a + h * i + h / 2) + f(a + h * i) / 2
2014-01-17 05:32:22 +00:00
end
2018-06-22 20:57:24 +00:00
return h/6 * (f(a) + f(b) + 4*s)
2014-01-17 05:32:22 +00:00
end
2018-06-22 20:57:24 +00:00
rst =
simpson(x -> x ^ 3, 0, 1, 100),
simpson(x -> 1 / x, 1, 100, 1000),
simpson(x -> x, 0, 5000, 5_000_000),
simpson(x -> x, 0, 6000, 6_000_000)
@show rst