Fortran Fortran output has lots of errors that I don't understand

Click For Summary
The discussion revolves around a Fortran 95 program intended to integrate the function x^2 from 0 to 1 using a Monte Carlo method. The user encounters multiple compilation errors related to the function definition and program structure. Key issues include the placement of the function x2 within the main program, which leads to confusion for the compiler. The solution involves adding an END statement after the PRINT statement to clearly delineate the end of the main program, allowing the function definition to be recognized correctly. After implementing this fix, the user successfully resolves the errors.
ngendler
Messages
20
Reaction score
0
I am trying to write a program that in Fortran 95 will integrate x^2 from 0 to 1. Easy right?? I'm getting errors, though, that I really don't understand. Here is my code:

program montecarlo2
implicit none
real :: fmax,iseed,srand,xmax,x2,x,y
!why do we need pi??
integer :: icount,nmax,ans0
iseed = 329048234
call srand(iseed)

nmax = 10000

!integrate x^2 from zero to one
icount = 0
xmax = 1
fmax = x2(xmax)
ans0 = 0.
do i=1,nmax
x = rand()
y = rand()
f = x2(x)
if(y.le.f/fmax) then
icount = icount+1
end if
ans0 = ans0 + x2(y)
end do
print *,dfloat(icount)/dfloat(nmax),ans0/dfloat(nmax)

function x2(x)
implicit none
x2 = x**2
end function x2

and here is the output:

montecarlo2.f95:26:

function x2(x)
1
Error: Unclassifiable statement at (1)
montecarlo2.f95:27.13:

implicit none
1
Error: Unexpected IMPLICIT NONE statement at (1)
montecarlo2.f95:28.2:

x2 = x**2
1
Error: 'x2' at (1) is not a variable
montecarlo2.f95:29.3:

end function x2
1
Error: Expecting END DO statement at (1)
Error: Unexpected end of file in 'montecarlo2.f95'

please help!
 
Technology news on Phys.org
You probably should have and END or END PROGRAM statement after the PRINT statement. You have not instructed the compiler that there are no more statements in the main program 'montecarlo2'. When the compiler sees a function definition, then it becomes confused.
 
Last edited:
Thank you, @SteamKing! It worked!
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 4 ·
Replies
4
Views
28K
  • · Replies 8 ·
Replies
8
Views
4K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
13
Views
8K
  • · Replies 10 ·
Replies
10
Views
6K
  • · Replies 5 ·
Replies
5
Views
15K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 9 ·
Replies
9
Views
5K
  • · Replies 2 ·
Replies
2
Views
3K