Do loop parameters considered as non-numeric characters - fortran

I am a Newbie to Fortran, facing a problem within a Do loop. I am programming a Fortran Code for a MEX File to be used within Matlab.
I assume it has a problem with the definition of k and z, but I don't see why. Maybe you guys have a hint for me what I am doing wrong. Thank you very much!
Error Message and Code
innerloops.F
do k = 1, 4
1
Error: Non-numeric character in statement label at (1)
innerloops.F
do k = 1, 4
1
Error: Unclassifiable statement at (1)
innerloops.F
do z = 1, 25
1
Error: Non-numeric character in statement label at (1)
innerloops.F
do z = 1, 25
Error: Unclassifiable statement at (1)
C Computational routine
subroutine innerloops(J,c1,c2,c3,c4,n1,n2,n3,n4,y,m,n)
mwSize m, n
integer k, z
real*8 J(m,n), y(4,1), c1, c2, c3, c4, n1, n2, n3, n4
real*8 QuadRuleX(25,2)
real*8 QuadRuleW(25,1)
real*8 X(5,1), r, t
real*8 P, c_h, n_h
integer h = 10
C Gaussian Points
X(1) = -.906179
X(2) = -.538469
X(3) = 0
X(4) = .538469
X(5) = .906179
C Corresponding QuadRule points
QuadRuleX(1,1) = X(1)
QuadRuleX(1,2) = X(1)
C .... (snipped it here for readability)
C Corresponding weights
QuadRuleW(1) = Y(1)*Y(1)
QuadRuleW(2) = Y(2)*Y(1)
C .... (snipped it here for readability)
do k = 1, 4
do z = 1, 25
r = QuadRuleX(z,1)
t = QuadRuleX(z,2)
P = shape(k,r,t)
c_h = c1*shape(k,r,t)
n_h = n1*shape(k,r,t)
y(k,1) = (P*((((h-1)*c_h)/(h-1)*c_h+1))*n_h*(2-n_h)-n_h)
continue
continue
return
end do
end subroutine innerloops
C defining the shape functions
Function shape(q,c,d)
implicit none
real q,c,d,P
if (q == 1) then
P = 1/4*(c-1)*(d-1)
else if (q == 2) then
P = -1/4*(c+1)*(d-1)
else if (q == 3) then
P = 1/4*(c+1)*(d+1)
else if (q == 4) then
P = -1/4*(c-1)*(d+1)
endif
return
end Function shape

By using a .F suffix the compiler by default assumes that you are using a fixed format source code. In fixed format certain columns are reserved for special purposes. Here it appears that your "do" has been mistakenly put into a column reserved for statement label (columns 1 through 5). Your statement has to fit between column 7 and 72 in a fixed-format fortran file. This is what the compiler was complaining about. As mentioned by others, your code also contain other errors that need to be fixed.
To make things simpler, you can use a free format instead by changing the suffix to .f90 and replacing the "C" comment indicator with "!".

Related

if statement to determine steady-state

My code below correctly solves a 1D heat equation for a function u(x,t). I now want to find the steady-state solution, the solution that no longer changes in time so it should satisfy u(t+1)-u(t) = 0. What is the most efficient way to find the steady-state solution? I show three different attempts below, but I'm not sure if either are actually doing what I want. The first and third have correct syntax, the second method has a syntax error due to the if statement. Each method is different due to the change in the if structure.
Method 1 :
program parabolic1
integer, parameter :: n = 10, m = 20
real, parameter :: h = 0.1, k = 0.005 !step sizes
real, dimension (0:n) :: u,v
integer:: i,j
real::pi,pi2
u(0) = 0.0; v(0) = 0.0; u(n) = 0.0; v(n) =0.0
pi = 4.0*atan(1.0)
pi2 = pi*pi
do i=1, n-1
u(i) = sin( pi*real(i)*h)
end do
do j = 1,m
do i = 1, n-1
v(i) = 0.5*(u(i-1)+u(i+1))
end do
t = real(j)*k !increment in time, now check for steady-state
!steady-state check: this checks the solutions at every space point which I don't think is correct.
do i = 1,n-1
if ( v(i) - u(i) .LT. 1.0e-7 ) then
print*, 'steady-state condition reached'
exit
end if
end do
do i = 1, n-1 !updating solution
u(i) = v(i)
end do
end do
end program parabolic1
Method 2 :
program parabolic1
integer, parameter :: n = 10, m = 20
real, parameter :: h = 0.1, k = 0.005 !step sizes
real, dimension (0:n) :: u,v
integer:: i,j
real::pi,pi2
u(0) = 0.0; v(0) = 0.0; u(n) = 0.0; v(n) =0.0
pi = 4.0*atan(1.0)
pi2 = pi*pi
do i=1, n-1
u(i) = sin( pi*real(i)*h)
end do
do j = 1,m
do i = 1, n-1
v(i) = 0.5*(u(i-1)+u(i+1))
end do
t = real(j)*k !increment in time, now check for steady-state
!steady-state check: (This gives an error message since the if statement doesn't have a logical scalar expression, but I want to compare the full arrays v and u as shown.
if ( v - u .LT. 1.0e-7 ) then
print*, 'steady-state condition reached'
exit
end if
do i = 1, n-1 !updating solution
u(i) = v(i)
end do
end do
end program parabolic1
Method 3 :
program parabolic1
integer, parameter :: n = 10, m = 20
real, parameter :: h = 0.1, k = 0.005 !step sizes
real, dimension (0:n) :: u,v
integer:: i,j
real::pi,pi2
u(0) = 0.0; v(0) = 0.0; u(n) = 0.0; v(n) =0.0
pi = 4.0*atan(1.0)
pi2 = pi*pi
do i=1, n-1
u(i) = sin( pi*real(i)*h)
end do
do j = 1,m
do i = 1, n-1
v(i) = 0.5*(u(i-1)+u(i+1))
end do
t = real(j)*k !increment in time, now check for steady-state
!steady-state check: Perhaps this is the correct expression I want to use
if( norm2(v) - norm2(u) .LT. 1.0e-7 ) then
print*, 'steady-state condition reached'
exit
end if
do i = 1, n-1 !updating solution
u(i) = v(i)
end do
end do
end program parabolic1
Without discussing which method to determine "closeness" is best or correct (not really being a programming problem) we can focus on what the Fortran parts of the methods are doing.
Method 1 and Method 2 are similar ideas (but broken in their execution), while Method 3 is different (and broken in another way).
Note also that in general one wants to compare the magnitude of the difference abs(v-u) rather than the (signed) difference v-u. With non-monotonic changes over iterations these are quite different.
Method 3 uses norm2(v) - norm2(u) to test whether the arrays u and v are similar. This isn't correct. Consider
norm2([1.,0.])-norm2([0.,1.])
instead of the more correct
norm2([1.,0.]-[0.,1.])
Method 2's
if ( v - u .LT. 1.0e-7 ) then
has the problem of being an invalid array expression, but the "are all points close?" can be written appropriately as
if ( ALL( v - u .LT. 1.0e-7 )) then
(You'll find other questions around here about such array reductions).
Method 1 tries something similar, but incorrectly:
do i = 1,n-1
if ( v(i) - u(i) .LT. 1.0e-7 ) then
print*, 'steady-state condition reached'
exit
end if
end do
This is incorrect in one big way, and one subtle way.
First, the loop is exited when the condition tests true the first time, with a message saying the steady state is reached. This is incorrect: you need all values close, while this is testing for any value close.
Second, when the condition is met, you exit. But you don't exit the time iteration loop, you exit the closeness testing loop. (exit without a construct name leaves the innermost do construct). You'll be in exactly the same situation, running again immediately after this innermost construct whether the tested condition is ever or never met (if ever met you'll get the message also). You will need to use a construct name on the time loop.
I won't show how to do that (again there are other questions here about that), because you also need to fix the test condition, by which point you'll be better off using if(all(... (corrected Method 2) without that additional do construct.
For Methods 1 and 2 you'll have something like:
if (all(v-u .lt 1e-7)) then
print *, "Converged"
exit
end if
And for Method 3:
if (norm2(v-u) .lt. 1e-7) then
print *, "Converged"
exit
end if

Can't input value in f(x) in this Fortran code?

program prob_1
implicit real*8(a-h, o-z)
f(x) = x**2-cos(x)
df(x) = 2*x+sin(x)
x0 = 0, x1 = 1
do i = 1, 3
if (f((x0+x1)/2) < 0)
x0 = (x0+x1)/2
else
x1 = (x0+x1)/2
end do
print *,"x = ", x
end program
I'm just starting to use Fortran 90.
Now I'm using Code::blocks but I don't know exactly which line the error exists on.
I guess the problem is f((x0+x1)/2) < 0 but don't know actually what is the real error.
what's problem is here?
Be advised that statement functions, the function definitions the OP uses, are obsolescent.
B.3.4 Statement functions
Statement functions are subject to a number of non intuitive restrictions and are a potential source of error because their syntax is easily confused with that of an assignment statement.
The internal function is a more generalized form of the statement function and completely supersedes it.
source: F2018 Standard
Also the notation REAL*8 or anything of that form has never been part of any Fortran standard (see here):
I would suggest to rewrite the code as:
program prob_1
implicit none
double precision :: x1,x0
integer :: i
x0 = 0; x1 = 1
do i = 1, 3
if (f((x0+x1)/2.0D0) < 0) then
x0 = (x0+x1)/2.0D0
else
x1 = (x0+x1)/2.0D0
endif
end do
print *,"x = ", (x0+x1)/2.0D0
contains
function f(x)
double precision, intent(in) :: x
double precision :: f
f = x**2-cos(x)
end function f
function df(x)
double precision, intent(in) :: x
double precision :: df
df = 2.0D0*x+sin(x)
end function df
end program
If you change your program as follows then it will compile:
program prob_1
implicit real*8(a-h, o-z)
f(x) = x**2-cos(x)
df(x) = 2*x+sin(x)
x0 = 0; x1 = 1
do i = 1, 3
if (f((x0+x1)/2) < 0) then
x0 = (x0+x1)/2
else
x1 = (x0+x1)/2
endif
end do
print *,"x = ", x
end program
As mentionned in the comments, you have to add the semicolon ; to separate statements in one line and you have to add the then as well as endif to your if condition.
Hope it helps.

How to exit from nested Fortran loops?

I'm trying to write a program (in Fortran 95) that finds the minimal decomposition of natural numbers up to N into a sum of at most 4 positive integers.
I've been trying to add and remove statements for a while to make it stop at only the minimal decomposition but I'm not getting anywhere. How do I make the program stop as soon as it's found the minimal decomposition?
PROGRAM SummeQuadrat
IMPLICIT NONE
real:: start,finish
integer:: a,b,c,d,g,x,y
write(*,*) "Max n"
read (*,*) y
call cpu_time(start)
do x=1,y,1
do a=0,x,1
do b=a,x-a,1
do c=b,x-b,1
do d=c,x-c,1
if (a**2+b**2+c**2+d**2 .eq. x) then
write(*,*) "x=",x,d,c,b,a
end if
end do
end do
end do
end do
end do
call cpu_time(finish)
write(*,*)finish-start
end program SummeQuadrat
As I explained in the comments, I am not sure you are asking only how to break out of the loops or for more.
You can jump out of any loop using the EXIT statement. To exit from a loop which is not the innermost loop you are currently in you use a labeled loop and use the label in the EXIT statement to exit that particular loop.
outer: do x = 1, y
do a = 0, x
do b = a, x-a
do c = b, x-b
do d = c, x-c
if (a**2+b**2+c**2+d**2 == x) then
write(*,*) "x=",x,d,c,b,a
if (minimal(a,b,c,d)) exit outer
end if
end do
end do
end do
end do
end do outer
Old thread, but it's kind of a fun problem so I thought I might post my own interpretation.
First off, if we cheat a little and peek at the solution it can be seen that all 4 squares are only needed when x=4**k*(8*m+7). Thus we can search cheaply for 1 or 2 square solutions and on failure decide by the above criterion whether to search for a 3- or 4-square solution.
Then when we structure our loops, count down from the largest a such that a**2 <= x, then the largest b <= a such that a**2+b**2 <= x and so on. This takes the problem from O(x**4) down to O(x**1.5) so it can go much quicker.
For output format, by judicious use of the colon format we can write a single format that prints out results in perhaps a more readable fashion.
! squares.f90 -- Prints out minimal decomposition x into squares
! for 1 <= x <= y (user input)
program squares
use ISO_FORTRAN_ENV, only: REAL64
implicit none
! Need this constant so we can take the square root of an
! integer.
real(REAL64), parameter :: half = 0.5_REAL64
real start, finish
integer a,b,c
integer amax,bmax,cmax,dmax
integer amin,bmin,cmin
integer x,y
! Format for printing out decomposition into squares
character(40) :: fmt = '(i0," = ",i0"**2":3(" + ",i0,"**2":))'
integer nzero
! Get uper bound from user
write(*,'(a)',advance='no') 'Please enter the max N:> '
read(*,*) y
call cpu_time(start)
! Loop over requested range
outer: do x = 1, y
amax = sqrt(x+half)
! Check for perfect square
if(amax**2 == x) then
write(*,fmt) x,amax
cycle outer
end if
! Check for sum of 2 squares
amin = sqrt(x/2+half)
try2: do a = amax, amin, -1
bmax = sqrt(x-a**2+half)
if(bmax > a) exit try2
if(a**2+bmax**2 == x) then
write(*,fmt) x,a,bmax
cycle outer
end if
end do try2
! If trailz(x) is even, then x = 4**k*z, where z is odd
! If further z = 8*m+7, then 4 squares are required, otherwise
! only 3 should suffice.
nzero = trailz(x)
if(iand(nzero,1)==0 .AND. ibits(x,nzero,3)==7) then
amin = sqrt(x/4+half)
do a = amax, amin, -1
bmax = sqrt(x-a**2+half)
bmin = sqrt((x-a**2)/3+half)
do b = min(bmax,a), bmin, -1
cmax = sqrt(x-a**2-b**2+half)
cmin = sqrt((x-a**2-b**2)/2+half)
do c = min(cmax,b), cmin, -1
dmax = sqrt(x-a**2-b**2-c**2+half)
if(a**2+b**2+c**2+dmax**2 == x) then
write(*,fmt) x,a,b,c,dmax
cycle outer
end if
end do
end do
end do
else
amin = sqrt(x/3+half)
do a = amax, amin, -1
bmax = sqrt(x-a**2+half)
bmin = sqrt((x-a**2)/2+half)
do b = min(bmax,a), bmin, -1
cmax = sqrt(x-a**2-b**2+half)
if(a**2+b**2+cmax**2 == x) then
write(*,fmt) x,a,b,cmax
cycle outer
end if
end do
end do
end if
! We should have a solution by now. If not, print out
! an error message and abort.
write(*,'(*(g0))') 'Failure at x = ',x
stop
end do outer
call cpu_time(finish)
write(*,'(*(g0))') 'CPU time = ',finish-start
end program squares

Nesting errors in FORTRAN

I'm creating a program that is required to read values from two arrays (ARR and MRK), counting each set of values (I,J) in order to determine their frequency for a third array (X). I've written the following so far, but nesting errors are preventing the program from compiling. Any help is greatly appreciated!
IMPLICIT NONE
REAL, DIMENSION (0:51, 0:51) :: MRK, ALT
INTEGER :: I, J !! FREQUENCY ARRAY ALLELES
INTEGER, PARAMETER :: K = 2
INTEGER :: M, N !! HAPLOTYPE ARRAY POSITIONS
INTEGER :: COUNTER = 0
REAL, DIMENSION(0:1,0:K-1):: X
ALT = 8
MRK = 8
X = 0
MRK(1:50,1:50) = 0 !! HAPLOTYPE ARRAY WITHOUT BUFFER AROUND OUTSIDE
ALT(1:50,1:50) = 0
DO I = 0, 1 !! ALTRUIST ALLELE
DO J = 0, K-1 !! MARKER ALLELE
DO M = 1, 50
DO N = 1, 50 !! READING HAPLOTYPE POSITIONS
IF ALT(M,N) = I .AND. MRK(M,N) = J THEN
COUNTER = COUNTER + 1
ELSE IF ALT(M,N) .NE. I .OR. MRK(M,N) .NE. J THEN
COUNTER = COUNTER + 0
END IF
X(I,J) = COUNTER/2500
COUNTER = 0
END DO
END DO
END DO
END DO
Your if syntax is incorrect. You should enclose the conditional expressions between brackets. Also, I think you should replace single = by a double == in the same expressions and maybe keep the syntax type to either == and /= or .eq. and .neq., but not mix them:
IF (ALT(M,N) == I .AND. MRK(M,N) == J) THEN
COUNTER = COUNTER + 1
ELSE IF (ALT(M,N) /= I .OR. MRK(M,N) /= J) THEN
COUNTER = COUNTER + 0
END IF
I don't know if in your actual program you do it, but you should probably use program program_name and end program program_name at the very beginning and very end of your code, respectively, where program_name is anything you want to call your program (no spaces allowed I think), although a simple end at the end would suffice.

What is the Basic Structure of a Function in FORTRAN?

This is something that's I've wanted to know recently, mostly out of curiousity. I'm in the mood to learn some old coding styles, and FORTRAN seems like a good place to start.
I guess I should help you guys out by providing a good starting point.
So how would this C procedure be written in FORTRAN?
int foo ( int x , int y )
{
int tempX = x ;
x += y / 2 ;
y -= tempX * 3 ; // tempX holds x's original value.
return x * y ;
}
I know the entire function could be a single line:
return ( x + ( y / 2 ) ) * ( y - ( x * 3 ) ) ;
But the point of me asking this question is to see how those four statements would be written individually in FORTRAN, not neccessarily combined into a single statement.
Don't blame me - you said old coding styles:
C234567
SUBROUTINE FOO(I,J,K)
C SAVE THE ORIGINAL VALUES
IORIG = I
JORIG = J
C PERFORM THE COMPUTATION
I = I + J/2
J = J - IORIG*3
K = I * J
C RESTORE VALUES
I = IORIG
J = JORIG
END SUBROUTINE FOO
I shudder as I write this, but
all variables are implicitly integers, since they start with letters between I and N
FORTRAN passes by reference, so reset I and J at the end to give the same effect as the original function (i.e. pass-by-value, so x and y were unchanged in the calling routine)
Comments start in column 1, actual statements start in column 7
Please, please, please never write new code like this unless as a joke.
Your function might look like this in Fortran
integer function foo(m, n)
integer i
i = m
m = m + n/2
n = n - i*3
foo = m*n
end function foo
You should be able to get started with any tutorial on Fortran. Some thing like this might help http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/fortran.html
cheers
See Functions and Subroutines:
INTEGER FUNCTION foo(i, j)
...
foo = 42
END
then later:
k = foo(1, 2)
Where do you learn FORTRAN from? Just take a look at the wikibooks!
Derived from the example, I'd say:
function func(x, y) result(r)
integer, intent(in) :: x, y
integer :: r
integer :: tempX
tempX = x
x = x / 2
y = y - tempX * 3
r = x * y
end function foo
Similar to above, but with a main program to illustrate how it would be called.
C2345678
program testfoo
implicit none
integer r, foo
r = foo(4,5)
print *, 'result = ', r
end
integer function foo(x,y)
integer x, y
integer tx, ty
tx = x + y / 2
ty = y - x * 3
foo = tx * ty
return
end
Note that this is Fortran 77, which is what I learned 23 years ago.
True old style in applying the rule IJKLMN for integer
C2345678
FUNCTION IFOO(I,J)
II = I + J/2
JJ = J - I*3
IFOO = II*JJ
END