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
the passed to
the subroutine as a
calling argument .
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
.
Coding
Program Mini_maxi
Implicit
none
integer :: i, step
real :: a , b , x(200) , y(200) , f, incr
Write(*,1) 'Starting Interval :'
1 format (a20)
read(*,7) a
7 format(F10.3)
Write(*,2)'Ending
Interval :'
2 format (a20)
read(*,10) b
10 format(F10.3)
Write(*,3)'Steps :'
3 format (a8)
read(*,11) step
11 format(I4,/)
Write (*,4)'No.','Values of x','Values of y'
4 format (a4,5x,a11,6x,a11)
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
Write (*,5)i, x(i),y(i)
5 format (i5,5x,f10.6,6x,f10.6)
end do
Call sub(x,y)
end program
subroutine
sub(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, s
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 sub2(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 sub2(y(1), y(i))
max_loc=x(i)
max_val=y(i)
end if
end do
write(*, 8) "Minimum value =",
min_val, ", location =", min_loc
8 format(/,/,A16, f10.3, A13, F10.3)
write(*, 9) "Maximum value =",
max_val, ", location =", max_loc
9 format(A16, f10.3, A13, F10.3)
end subroutine
subroutine sub2(a,b)
implicit none
real :: a, b, s
s=a
a=b
b=s
end subroutine
Input Data
Output result ::
No comments:
Post a Comment