Skip to content

Instantly share code, notes, and snippets.

@yeukhon
Last active June 14, 2019 04:49
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 yeukhon/d2404ec2e5edb8e935e89e2c5e0f5088 to your computer and use it in GitHub Desktop.
Save yeukhon/d2404ec2e5edb8e935e89e2c5e0f5088 to your computer and use it in GitHub Desktop.
program integral
implicit none
! we will solve integral of x^2 using the Trapezoidal Rule
integer :: n
real :: a, b, step, delta, coeff, f0, fn, inner_total, x
! We integrate x^2 from 0 to 4 with n intervals
a = 0.0
b = 4.0
n = 8
! given n interval, the step is b/n
step = b / n
! print *, 'step ', step
! the formula looks like this
! delta(x)/2 * [f(x0) + 2f(x1) + 2f(x2) + ... + f(x_n)]
delta = (b-a) / n
coeff = delta / 2
!print *, 'delta ', delta
!print *, 'coeff ', coeff
! here we calulate f(x0) and f(x_n) where f(x) = x^2
f0 = a**2
fn = b**2
! now we calculate the rest of the intervals
! step in do-loop must be an integer, so iterate n-2 times
x = a + step
do n = 1, n - 2, 1
x = x + step
inner_total = inner_total + 2 * (x**2)
end do
print *, coeff * (f0 + inner_total + fn)
end program integral
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment