Unclassifiable statement at (1) when calling a function - fortran

I'm relatively new to Fortran and I have an assignment to find quadrature weights and points where the points are the zeros of the nth legendre polynomial (found using Newton's method); I made functions to find the value of Pn(x) and P'n(x) to sub into Newton's method.
However when actually using the functions in my quadrature subroutine it comes back with:
Coursework2a.f90:44.3:
x = x - P(n,x)/dP(n,x)
1
Error: Unclassifiable statement at (1)
Does anybody know any reasons why this statement could be classed as unclassifiable?
subroutine Quadrature(n)
implicit none
integer, parameter :: dpr = selected_real_kind(15) !Double precision
real(dpr) :: P, dP, x, x_new, error = 1, tolerance = 1.0E-6, Pi = 3.141592 !Define Variables
integer, intent(in) :: n
integer :: i
!Next, find n roots. Start with first guess then iterate until error is greater than some tolerance.
do i = 1,n
x = -cos(((2.0*real(i)-1.0)/2.0*real(n))*Pi)
do while (error > tolerance)
x_new = x
x = x - P(n,x)/dP(n,x)
error = abs(x_new-x)
end do
print *, x
end do
end subroutine Quadrature

The line
x = -cos(((2.0*real(i)-1.0)/2.0*real(n))*Pi)
is likely missing a set of brackets around the denominator. As it is, the line divides (2.0*real(i)-1.0) by 2.0, then multiplies the whole thing by real(n). This may be why you get the same root for each loop.

real function p(n,x)
real::n,x
p=2*x**3 !or put in the function given to you.
end function
real function dp(n,x)
real::n,x
dp=6*x**2 !you mean derivative of polynomial p, I guess.
end function
Define function like this separately outside the main program. Inside the main program declare the functions like:
real,external::p, dp

Related

Computing the Jacobian matrix in Fortran

In Newton's method, to solve a nonlinear system of equations we need to find the Jacobian matrix and the determinant of the inverse of the Jacobian matrix.
Here are my component functions,
real function f1(x,y)
parameter (pi = 3.141592653589793)
f1 = log(abs(x-y**2)) - sin(x*y) - sin(pi)
end function f1
real function f2(x,y)
f2 = exp(x*y) + cos(x-y) - 2
end function f2
For the 2x2 case I am computing the Jacobian matrix and determinant of the inverse of Jacobian matrix like this,
x = [2,2]
h = 0.00001
.
.
! calculate approximate partial derivative
! you can make it more accurate by reducing the
! value of h
j11 = (f1(x(1)+h,x(2))-f1(x(1),x(2)))/h
j12 = (f1(x(1),x(2)+h)-f1(x(1),x(2)))/h
j21 = (f2(x(1)+h,x(2))-f2(x(1),x(2)))/h
j22 = (f2(x(1),x(2)+h)-f2(x(1),x(2)))/h
! calculate the Jacobian
J(1,:) = [j11,j12]
J(2,:) = [j21,j22]
! calculate inverse Jacobian
inv_J(1,:) = [J(2,2),-J(1,2)]
inv_J(2,:) = [-J(2,1),J(1,1)]
DET=J(1,1)*J(2,2) - J(1,2)*J(2,1)
inv_J = inv_J/DET
.
.
How do I in Fortran extend this to evaluate a Jacobian for m functions evaluated at n points?
Here is a more flexible jacobian calculator.
The results with the 2×2 test case are what you expect
arguments (x)
2.00000000000000
2.00000000000000
values (y)
1.44994967586787
53.5981500331442
Jacobian
0.807287239448229 3.30728724371454
109.196300248300 109.196300248300
I check the results against a symbolic calculation for the given inputs of
Console.f90
program Console1
use ISO_FORTRAN_ENV
implicit none
! Variables
integer, parameter :: wp = real64
real(wp), parameter :: pi = 3.141592653589793d0
! Interfaces
interface
function fun(x,n,m) result(y)
import
integer, intent(in) :: n,m
real(wp), intent(in) :: x(m)
real(wp) :: y(n)
end function
end interface
real(wp) :: h
real(wp), allocatable :: x(:), y(:), J(:,:)
! Body of Console1
x = [2d0, 2d0]
h = 0.0001d0
print *, "arguments"
print *, x(1)
print *, x(2)
y = test(x,2,2)
print *, "values"
print *, y(1)
print *, y(2)
J = jacobian(test,x,2,h)
print *, "Jacobian"
print *, J(1,:)
print *, J(2,:)
contains
function test(x,n,m) result(y)
! Test case per original question
integer, intent(in) :: n,m
real(wp), intent(in) :: x(m)
real(wp) :: y(n)
y(1) = log(abs(x(1)-x(2)**2)) - sin(x(1)*x(2)) - sin(pi)
y(2) = exp(x(1)*x(2)) + cos(x(1)-x(2)) - 2
end function
function jacobian(f,x,n,h) result(u)
procedure(fun), pointer, intent(in) :: f
real(wp), allocatable, intent(in) :: x(:)
integer, intent(in) :: n
real(wp), intent(in) :: h
real(wp), allocatable :: u(:,:)
integer :: j, m
real(wp), allocatable :: y1(:), y2(:), e(:)
m = size(x)
allocate(u(n,m))
do j=1, m
e = element(j, m) ! Get kronecker delta for j-th value
y1 = f(x-e*h/2,n,m)
y2 = f(x+e*h/2,n,m)
u(:,j) = (y2-y1)/h ! Finite difference for each column
end do
end function
function element(i,n) result(e)
! Kronecker delta vector. All zeros, except the i-th value.
integer, intent(in) :: i, n
real(wp) :: e(n)
e(:) = 0d0
e(i) = 1d0
end function
end program Console1
I will answer about evaluation in different points. This is quite simple. You just need an array of points, and if the points are in some regular grid, you may not even need that.
You may have an array of xs and array of ys or you can have an array of derived datatype with x and y components.
For the former:
real, allocatable :: x(:), y(:)
x = [... !probably read from some data file
y = [...
do i = 1, size(x)
J(i) = Jacobian(f, x(i), y(i))
end do
If you want to have many functions at the same time, the problem is always in representing functions. Even if you have an array of function pointers, you need to code them manually. A different approach is to have a full algebra module, where you enter some string representing a function and you can evaluate such function and even compute derivatives symbolically. That requires a parser, an evaluator, it is a large task. There are libraries for this. Evaluation of such a derivative will be slow unless further optimizing steps (compiling to machine code) are undertaken.
Numerical evaluation of the derivative is certainly possible. It will slow the convergence somewhat, depending on the order of the approximation of the derivative. You do a difference of two points for the numerical derivative. You can make an interpolating polynomial from values in multiple points to get a higher-order approximation (finite difference approximations), but that costs machine cycles.
Normally we can use auto difference tools as #John Alexiou mentioned. However in practise I prefer using MATLAB to analytically solve out the Jacobian and then use its build-in function fortran() to convert the result to a f90 file. Take your function as an example. Just type these into MATLAB
syms x y
Fval=sym(zeros(2,1));
Fval(1)=log(abs(x-y^2)) - sin(x*y) - sin(pi);
Fval(2)=exp(x*y) + cos(x-y) - 2;
X=[x;y];
Fjac=jacobian(Fval,X);
fortran(Fjac)
which will yield
Fjac(1,1) = -y*cos(x*y)-((-(x-y**2)/abs(-x+y**2)))/abs(-x+y**2)
Fjac(1,2) = -x*cos(x*y)+(y*((-(x-y**2)/abs(-x+y**2)))*2.0D0)/abs(-
&x+y**2)
Fjac(2,1) = -sin(x-y)+y*exp(x*y)
Fjac(2,2) = sin(x-y)+x*exp(x*y)
to you. You just get an analytical Jacobian fortran function.
Meanwhile, it is impossible to solve the inverse of a mxn matrix because of rank mismatching. You should simplify the system of equations to get a nxn Jacobin.
Additionally, when we use Newton-Raphson's method we do not solve the inverse of the Jacobin which is time-consuming and inaccurate for a large system. An easy way is to use dgesv in LAPACK for dense Jacobin. As we only need to solve the vector x from system of linear equations
Jx=-F
dgesv use LU decomposition and Gaussian elimination to solve above system of equations which is extremely faster than solving inverse matrix.
If the system of equations is large, you can use UMFPACK and its fortran interface module mUMFPACK to solve the system of equations in which J is a sparse matrix. Or use subroutine ILUD and LUSOL in a wide-spread sparse matrix library SPARSEKIT2.
In addition to these, there are tons of other methods which try to solve the Jx=-F faster and more accurate such as Generalized Minimal Residual (GMRES) and Stabilized Bi-Conjugate Gradient (BICGSTAB) which is a strand of literature.

Dummy argument not agreeing with actual argument when passing function

I'm trying to implement Newton's method but I'm getting a confusing error message. In my code you'll see I called external with f1 and f2 which I assumes tells the computer to look for the function but it's treating them as variables based on the error message. I've read the stack overflow posts similar to my issue but none of the solutions seem to work. I've tried with and without the external but the issue still persists. Hoping someone could see what I'm missing.
implicit none
contains
subroutine solve(f1,f2,x0,n, EPSILON)
implicit none
real(kind = 2), external:: f1, f2
real (kind = 2), intent(in):: x0, EPSILON
real (kind = 2):: x
integer, intent(in):: n
integer:: iteration
x = x0
do while (abs(f1(x))>EPSILON)
iteration = iteration + 1
print*, iteration, x, f1(x)
x = x - (f1(x)/f2(x))
if (iteration >= n) then
print*, "No Convergence"
stop
end if
end do
print*, iteration, x
end subroutine solve
end module newton
Program Lab10
use newton
implicit none
integer, parameter :: n = 1000 ! maximum iteration
real(kind = 2), parameter :: EPSILON = 1.d-3
real(kind = 2):: x0, x
x0 = 3.0d0
call solve(f(x),fp(x),x0,n, EPSILON)
contains
real (kind = 2) function f(x) ! this is f(x)
implicit none
real (kind = 2), intent(in)::x
f = x**2.0d0-1.0d0
end function f
real (kind = 2) function fp(x) ! This is f'(x)
implicit none
real (kind = 2), intent(in)::x
fp = 2.0d0*x
end function fp
end program Lab10```
You seem to be passing function results to your subroutine and not the functions themselves. Remove (x) when calling solve() and the problem will be resolved. But more importantly, this code is a prime example of how to not program in Fortran. The attribute external is deprecated and you better provide an explicit interface. In addition, what is the meaning of kind = 2. Gfortran does not even comprehend it. Even if it comprehends the kind, it is not portable. Here is a correct portable modern implementation of the code,
module newton
use iso_fortran_env, only: RK => real64
implicit none
abstract interface
pure function f_proc(x) result(result)
import RK
real(RK), intent(in) :: x
real(RK) :: result
end function f_proc
end interface
contains
subroutine solve(f1,f2,x0,n, EPSILON)
procedure(f_proc) :: f1, f2
real(RK), intent(in) :: x0, EPSILON
integer, intent(in) :: n
real(RK) :: x
integer :: iteration
x = x0
do while (abs(f1(x))>EPSILON)
iteration = iteration + 1
print*, iteration, x, f1(x)
x = x - (f1(x)/f2(x))
if (iteration >= n) then
print*, "No Convergence"
stop
end if
end do
print*, iteration, x
end subroutine solve
end module newton
Program Lab10
use newton
integer, parameter :: n = 1000 ! maximum iteration
real(RK), parameter :: EPSILON = 1.e-3_RK
real(RK) :: x0, x
x0 = 3._RK
call solve(f,fp,x0,n, EPSILON)
contains
pure function f(x) result(result) ! this is f(x)
real (RK), intent(in) :: x
real (RK) :: result
result = x**2 - 1._RK
end function f
pure function fp(x) result(result) ! This is f'(x)
real (RK), intent(in) :: x
real (RK) :: result
result = 2 * x
end function fp
end program Lab10
If you expect to pass nonpure functions to the subroutine solve(), then remove the pure attribute. Note the use of real64 to declare 64-bit (double precision) real kind. Also notice how I have used _RK suffix to assign 64-bit precision to real constants. Also, notice I changed the exponents from real to integer as it is multiplication is more efficient than exponentiation computationally. I hope this answer serves more than merely the solution to Lab10.

IMSL ppval function

I am trying to use PPVAL function from the IMSL library, to evaluate a piecewise polynomial, similar to MATLAB's ppval function.
Sadly, I could not understand well the documentation on how to properly use the function.
I tried to evaluate a simple polynomial.
The polynomials p(x) = 1 and p(x) = x were ok. What I don't understand is when I try to get higher degree polynomials.
The program below tries to evaluate the polynomial p(x)=x^4:
program main
include 'LINK_FNL_SHARED.h'
USE PPVAL_INT
implicit none
double precision :: x(11), y(11)
double precision :: BREAK(2),PPCOEF(5,1)
integer :: ii
break = [0.0d0,10.0d0] ! breakpoints in increasing order
PPCOEF(:,1) = [0.0d0,0.0d0,0.0d0,0.0d0,1.0d0] ! polynomial coefficients
x = dble([0,1,2,3,4,5,6,7,8,9,10])
do ii=1,11
y(ii) = PPVAL(x(ii),break,PPCOEF)
end do
print *, 'x = ', x
print *, 'y = ', y
pause
end program main
But the function returns the polynomial p(x) = x^4/4!.
For degrees 2,3 and 5, the return is always, p(x) = x^2/2!, p(x)=x^3/3!, p(x)=x^5/5!. Why does this factor appear in the ppval function? Why can't I just supply the polynomial coefficients and evaluate it?
Is there another simpler function to evaluate polynomials in Fortran, like MATLAB polyval?

How to calculate several different random numbers from normal dist? using fortran

I have to find 'n' random numbers from a normal distribution given the mean and standard deviation. I have figure out how to get a random number, but when try to loop it to get several different random numbers, it gives me the same number x amount of times?
program prac10
implicit none
real :: mu, sigma
integer :: i
!print*, "mean and stdev?"
!read*, mu, sigma
mu=1.1
sigma=0.1
do i=1, 2 # here is the part I think I am stuck on??
call normal(mu,sigma)
enddo
end program
subroutine normal(mu,sigma)
implicit none
integer :: i
integer :: n
real :: u, v, z, randnum
real :: mu, sigma
real :: pi=3.141593
call RANDOM_SEED()
call RANDOM_NUMBER(u)
call RANDOM_NUMBER(v)
z=sqrt(-2*log(u))*cos(2*pi*v)
randnum=mu+sigma*z
print*, randnum
end subroutine
particularly the part where I should be looping/repeating. I used from 1:2, replacing n with 2 for now so that I wouldn't have to input it every time I try to run it
The most important fact is that you must not call RANOM_SEED repeatedly. It is supposed to be called only once.
It is also good to modify the subroutine to generate the number and pass it further. Notice also the change of formatting to make it more readable and the change in the value of pi.
program prac10
implicit none
real :: mu, sigma, x
integer :: i
call RANDOM_SEED()
mu = 1.1
sigma = 0.1
do i = 1, 2
call normal(x,mu,sigma)
print *, x
end do
end program
subroutine normal(randnum,mu,sigma)
implicit none
integer :: i
integer :: n
real :: u, v, z, randnum
real :: mu, sigma
real :: pi = acos(-1.0)
call RANDOM_NUMBER(u)
call RANDOM_NUMBER(v)
z = sqrt(-2*log(u)) * cos(2*pi*v)
randnum = mu + sigma*z
end subroutine

Usage of Fortran statement functions

I read about statement functions, such as the example:
C(F) = 5.0*(F - 32.0)/9.0
Isn't this the same as:
C = 5.0*(F - 32.0)/9.0
i.e. without the function part, or maybe I'm missing something?
If they're not the same, when do I need to use a statement function?
C = 5.0*(F - 32.0)/9.0
is just assignment to a variable C, it can be anywhere and is evaluated once every time when the program flow reaches it.
C(F) = 5.0*(F - 32.0)/9.0
is a statement function, and can be evaluated any time it is in the scope by, e.g., C(100) which returns approximately 37.8.
From some code
xx(i) = dx*i
f(a) = a*a
do i = 1, nx
x = xx(i)
print *, f(x)
end do
The f(x) in the print statement is evaluated with each new value of x and yields a new value. The value of x is also result of evaluation of the statement function xx on the previous line.
But statement functions are now (in Fortran 95) declared obsolete. Better use internal functions in any new code. E.g.,
program p
implicit none
!declarations of variables x, i, nx, dx
do i = 1, nx
x = xx(i)
print *, f(x)
end do
contains
real function xx(i)
integer, intent(in) :: i
xx = dx*i
end function
real function f(a)
real, intent(in) :: a
f = a*a
end function
end program