Fortran编写子程序,给出范围[-1,3]内函数f(x)=x³-5x²+5x+2的最小值。输入参数:x的最大值,最小值,总数目,函数名。输出参数:函数最小值及对应的x。要求使用内置函数minval和minloc求数组最小值及其位置
时间: 2024-05-10 08:19:42 浏览: 53
下面是Fortran编写的子程序实现:
```
subroutine find_min(x_min, x_max, n, f_name, f_min, x_min_val)
implicit none
integer, intent(in) :: n
real, intent(in) :: x_min, x_max
character(len=*), intent(in) :: f_name
real, intent(out) :: f_min, x_min_val
real :: x, dx
real, dimension(n) :: f_values
integer :: min_index
integer :: i
interface
real function f(x)
real, intent(in) :: x
end function
end interface
dx = (x_max - x_min) / (n - 1)
do i = 1, n
x = x_min + (i - 1) * dx
f_values(i) = f(x)
end do
f_min = minval(f_values)
min_index = minloc(f_values)
x_min_val = x_min + (min_index - 1) * dx
write(*,*) 'The minimum value of ', trim(f_name), ' is ', f_min, ' at x = ', x_min_val
contains
real function f(x)
real, intent(in) :: x
f = x**3 - 5.0 * x**2 + 5.0 * x + 2.0
end function f
end subroutine find_min
```
在主程序中,可以这样调用这个子程序:
```
program main
real :: x_min = -1.0, x_max = 3.0, f_min, x_min_val
integer :: n = 100
character(len=30) :: f_name
f_name = 'f(x) = x^3 - 5x^2 + 5x + 2'
call find_min(x_min, x_max, n, f_name, f_min, x_min_val)
end program main
```
这个子程序使用了内置函数minval和minloc来求数组最小值及其位置,从而找到函数的最小值及其对应的x。
阅读全文