Skip to content

Instantly share code, notes, and snippets.

@IshitaTakeshi
Created June 29, 2017 01:06
Show Gist options
  • Save IshitaTakeshi/136878748ba6f0b4cc52b95b5086598c to your computer and use it in GitHub Desktop.
Save IshitaTakeshi/136878748ba6f0b4cc52b95b5086598c to your computer and use it in GitHub Desktop.
Numerical Integration
using Base.Test
function integrate(f, a, b, n_samples=100)
assert(b > a)
h = (b - a) / n_samples
xs = linspace(a, b, n_samples)
ys = [f(x) for x in xs]
h * ((ys[1] + ys[end]) / 2 + sum(ys[2:end-1]))
end
function test_integrate()
@test abs(integrate(sin, 0, 2π, 100) - 0) < 1e-8
@test abs(integrate(cos, 0, π/2, 1e5) - 1) < 1e-3
end
function run_homework()
println(
"Integration of 4 / (1 + x^2) in range [0, 1] : " *
"$(integrate(x -> 4 / (1+x^2), 0, 1, 10))"
)
println(
"Integration of sin(100x) + sin(57x) + 5 in range [0, π/2] : " *
"$(integrate(x -> sin(100x) + sin(57x) + 5, 0, π/2, 10))"
)
end
test_integrate()
run_homework()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment