How to Make a Variable Global in mnbrak.f90?

  • Thread starter Thread starter winiepu
  • Start date Start date
  • Tags Tags
    Numerical
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
winiepu
Messages
3
Reaction score
0
The following code is just an example. I try to apply mnbrak.f90 to my function f=(x-i)^2. I want to make i globle variable. If I use internal procedure, I can not use mnbrak.f90, since it can not accept the internal procedure. How do I deal with it? Thanks!

PROGRAM xbrent
USE nr
USE nrtype
IMPLICIT NONE

INTEGER(i4b) :: i
REAL(sp) :: ax, bx, cx, fa, fb, fc
!real, external:: f
! common i

DO i=1,10
ax=i-0.5_sp
bx=i+0.5_sp
CALL mnbrak(ax, bx, cx, fa, fb, fc, f)
!$ WRITE(*,'(1x,t13,a,t25,a,t37,a)') 'A','B','C'
!$ WRITE(*,'(1x,a3,t5,3f12.6)') 'X',ax,bx,cx
!$ WRITE(*,'(1x,a3,t5,3f12.6)') 'F',fa,fb,fc
write(*,*) f(ax),f(bx)
END DO

contains

FUNCTION f(x)
USE nr
USE nrtype
IMPLICIT NONE
REAL(sp) ::f,x
!common i
f=(x-i)**2.0_sp
END FUNCTION f

END PROGRAM xbrent
 
Physics news on Phys.org


Thank you for sharing your code and question. It seems like you are trying to use the mnbrak.f90 subroutine with your own function f=(x-i)^2, where i is a global variable. However, you are having trouble using an internal procedure with the mnbrak subroutine.

One solution to this issue could be to declare the global variable i as a module variable. This way, it can be accessed by both the main program and the internal procedure. You can do this by creating a module that contains the variable i and then importing it into both the main program and the internal procedure. Here is an example:

MODULE globals
INTEGER(i4b) :: i ! declare i as a module variable
END MODULE globals

PROGRAM xbrent
USE nr
USE nrtype
USE globals ! import the module containing i
IMPLICIT NONE

REAL(sp) :: ax, bx, cx, fa, fb, fc

DO i=1,10
ax=i-0.5_sp
bx=i+0.5_sp
CALL mnbrak(ax, bx, cx, fa, fb, fc, f)
WRITE(*,'(1x,a3,t5,3f12.6)') 'X',ax,bx,cx
WRITE(*,'(1x,a3,t5,3f12.6)') 'F',fa,fb,fc
write(*,*) f(ax),f(bx)
END DO

contains

FUNCTION f(x)
USE nr
USE nrtype
USE globals ! import the module containing i
IMPLICIT NONE
REAL(sp) ::f,x
f=(x-i)**2.0_sp
END FUNCTION f

END PROGRAM xbrent

By declaring i as a module variable, it can now be used in both the main program and the internal procedure. I hope this helps with your code! Let me know if you have any further questions.