Skip to content

Commit cb9d037

Browse files
test for trapezoid.f90
1 parent fa95858 commit cb9d037

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
!> Test program for the Trapezoidal Rule module
2+
!!
3+
!! Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed)
4+
!! in Pull Request: #32
5+
!! https://github.com/TheAlgorithms/Fortran/pull/32
6+
!!
7+
!! Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request
8+
!! addressing bugs/corrections to this file. Thank you!
9+
!!
10+
!! This program provides test cases to validate the trapezoidal_rule module against known integral values.
11+
12+
13+
program test_trapezoidal_rule
14+
use trapezoidal_rule
15+
implicit none
16+
17+
real(dp) :: lower_bound, upper_bound, integral_result, expected
18+
real(dp), parameter :: pi = 4.d0*DATAN(1.d0) ! Define Pi. Ensures maximum precision available on any architecture
19+
20+
integer :: panels_number
21+
22+
! Test 1: ∫ x^2 dx from 0 to 1 (Exact result = 1/3 ≈ 0.3333)
23+
lower_bound = 0.0_dp
24+
upper_bound = 1.0_dp
25+
panels_number = 1000000
26+
expected = 1.0_dp / 3.0_dp
27+
call trapezoid(integral_result, lower_bound, upper_bound, panels_number, f_x_squared)
28+
call assert_test(integral_result, expected, "Test 1: ∫ x^2 dx from 0 to 1")
29+
30+
! Test 2: ∫ x^2 dx from 0 to 2 (Exact result = 8/3 ≈ 2.6667)
31+
lower_bound = 0.0_dp
32+
upper_bound = 2.0_dp
33+
panels_number = 1000000
34+
expected = 8.0_dp / 3.0_dp
35+
call trapezoid(integral_result, lower_bound, upper_bound, panels_number, f_x_squared)
36+
call assert_test(integral_result, expected, "Test 2: ∫ x^2 dx from 0 to 2")
37+
38+
! Test 3: ∫ sin(x) dx from 0 to π (Exact result = 2)
39+
lower_bound = 0.0_dp
40+
upper_bound = pi
41+
panels_number = 1000000
42+
expected = 2.0_dp
43+
call trapezoid(integral_result, lower_bound, upper_bound, panels_number, sin_function)
44+
call assert_test(integral_result, expected, "Test 3: ∫ sin(x) dx from 0 to π")
45+
46+
contains
47+
48+
! Function for x^2
49+
real(dp) function f_x_squared(x)
50+
real(dp), intent(in) :: x
51+
f_x_squared = x**2
52+
end function f_x_squared
53+
54+
! Function for sin(x)
55+
real(dp) function sin_function(x)
56+
real(dp), intent(in) :: x
57+
sin_function = sin(x)
58+
end function sin_function
59+
60+
! Assertion subroutine
61+
subroutine assert_test(result, expected, test_name)
62+
real(dp), intent(in) :: result, expected
63+
character(len=*), intent(in) :: test_name
64+
real(dp), parameter :: tol = 1.0e-5_dp
65+
66+
if (abs(result - expected) < tol) then
67+
print *, test_name, " PASSED"
68+
else
69+
print *, test_name, " FAILED"
70+
print *, " Expected: ", expected
71+
print *, " Got: ", result
72+
stop 1
73+
end if
74+
end subroutine assert_test
75+
76+
end program test_trapezoidal_rule

0 commit comments

Comments
 (0)