Write a subroutine that attempts to locate the maximum and minimum values of an arbitrary function over a certain range . The function being evaluated should be passed to the subroutine as a calling argument.
The main program should pass to the subroutine the function
Program Maxi_Mini
implicit none
integer:: i, step
real:: a, b, x(200), y(200), f, incr
open(2, file="input.dat")
open(3, file="output.dat")
read(2, 7) a
7 format(/,F10.3)
read(2,10) b
10 format(/,F10.3)
read(2,11) step
11 format(/,I4)
incr=(b - a)/Float(step - 1)
do i= 1, step
x(i)= a + (i-1)*incr
y(i)= x(i)**3 - 5*x(i)**2 +5*x(i) +2
end do
Call subprog(x,y)
end program
subroutine subprog(x,y) ! x and y is x and F(x) value
implicit none
integer::i, j, iptr
real::x(200), y(200), min_loc, max_loc, min_val, max_val, temp
min_loc=x(1)
max_loc=x(1)
min_val=y(1)
max_val=y(1)
do i= 2, 200
if(y(1)>y(i)) then ! ( finding Minimum )
call swap(y(1), y(i))
min_loc=x(i)
min_val=y(i)
end if
end do
do i= 2, 200
if(y(1)<y(i)) then ! ( finding Maximum)
call swap(y(1), y(i))
max_loc=x(i)
max_val=y(i)
end if
end do
write(3, 8) "Minimum value =", min_val, ", location =", min_loc
8 format(A16, f10.3, A13, F10.3)
write(3, 9) "Maximum value =", max_val, ", location =", max_loc
9 format(A16, f10.3, A13, F10.3)
end subroutine
subroutine swap(a,b)
implicit none
real:: a, b, temp
temp=a
a=b
b=temp
end subroutine
The main program should pass to the subroutine the function
f(x) = x3 –
5x2 +5x +2 and search for the minimum and maximum in 200 steps over the range -1 ≤ x ≤ 3 . The subroutine should have the following output arguments minimum value , location of minimum value ,maximum value and location of maximum value.
Program Maxi_Mini
implicit none
integer:: i, step
real:: a, b, x(200), y(200), f, incr
open(2, file="input.dat")
open(3, file="output.dat")
read(2, 7) a
7 format(/,F10.3)
read(2,10) b
10 format(/,F10.3)
read(2,11) step
11 format(/,I4)
incr=(b - a)/Float(step - 1)
do i= 1, step
x(i)= a + (i-1)*incr
y(i)= x(i)**3 - 5*x(i)**2 +5*x(i) +2
end do
Call subprog(x,y)
end program
subroutine subprog(x,y) ! x and y is x and F(x) value
implicit none
integer::i, j, iptr
real::x(200), y(200), min_loc, max_loc, min_val, max_val, temp
min_loc=x(1)
max_loc=x(1)
min_val=y(1)
max_val=y(1)
do i= 2, 200
if(y(1)>y(i)) then ! ( finding Minimum )
call swap(y(1), y(i))
min_loc=x(i)
min_val=y(i)
end if
end do
do i= 2, 200
if(y(1)<y(i)) then ! ( finding Maximum)
call swap(y(1), y(i))
max_loc=x(i)
max_val=y(i)
end if
end do
write(3, 8) "Minimum value =", min_val, ", location =", min_loc
8 format(A16, f10.3, A13, F10.3)
write(3, 9) "Maximum value =", max_val, ", location =", max_loc
9 format(A16, f10.3, A13, F10.3)
end subroutine
subroutine swap(a,b)
implicit none
real:: a, b, temp
temp=a
a=b
b=temp
end subroutine