Problems with the Trapezoidal Rule - fortran

I'm having some troubles to calcule the integral of e^x inside and interval [b.a] using fortran.
I think I'm doing something wrong in the funcion calls. Thanks for helping me.
program trapezium
implicit none
integer :: i, n, b, a
real :: sumation, mean, deltax, f(i), integral
! The value of the integral using the trapezium rule can be found using
! integral = (b - a)*((f(a) +f(b))/2 + sumation_1_n-1 )/n
write(*,*) "type the limits b, a and the number of intervals"
read *, b, a, n
deltax = (b - a)/n
mean = (f(a) + f(b))/2
sumation = 0
do i = 1, n-1
sumation = sumation + f(i)
end do
integral = deltax*(mean + sumation)
write (*,*) "the value of the integral using the trapezoidal method is", integral
end program
function f(x)
real :: f(x)
integer :: x
f(x) = EXP(x)
end function

There are a couple of issues with your code:
f is a function, but at the same time you define an array f(i)
When defining an array of fixed size, the size has to be known at compile time. So real :: f(i) is only valid for a constant i
exp() expects a real variable, not an integer
Integer arithmetic might lead to unexpected results: 1/2 = 0 and not 0.5!
What about (This does not try to fix the maths, though - see my comment):
module functions
contains
function f(x)
implicit none
real :: f
integer,intent(in) :: x
f = EXP(real(x))
end function
end module
program trapezium
use functions
implicit none
integer :: i, n, b, a
real :: sumation, mean, deltax, integral
! The value of the integral using the trapezium rule can be found using
! integral = (b - a)*((f(a) +f(b))/2 + sumation_1_n-1 )/n
write(*,*) "type the limits b, a and the number of intervals"
read *, b, a, n
deltax = real(b - a)/real(n)
mean = (f(a) + f(b))/2
sumation = 0
do i = 1, n-1
sumation = sumation + f(i)
end do
integral = deltax*(mean + sumation)
write (*,*) "the value of the integral using the trapezoidal method is", integral
end program
Note that the use of modules enables the compiler to check for the arguments of the function. Additionally, you do not need to define the return value of the function in the main program.

Related

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.

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

How can I reduce floating-point error in a cubic equation solver?

I'm using the following algorithm to solve a cubic polynomial equation (x^3 + ax^2 + bx + c = 0):
function find_roots(a, b, c, lower_bound, upper_bound)
implicit none
real*8, intent(in) :: a, b, c, lower_bound, upper_bound
real*8 :: find_roots
real*8 :: Q, R, theta, x, Au, Bu
integer :: i, iter
Q = (a**2 - 3.D0*b)/9.D0
R = (2.D0*a**3 - 9.D0*a*b + 27.D0*c)/54.D0
!If roots are all real, get root in range
if (R**2.lt.Q**3) then
iter = 0
theta = acos(R/sqrt(Q**3))
!print *, "theta = ", theta
do i=-1,1
iter = iter+1
x = -2.D0*sqrt(Q)*cos((theta + dble(i)*PI*2.D0)/3.D0)-a/3.D0
!print *, "iter = ", iter, "root = ", x
if ((x.ge.lower_bound).and.(x.le.upper_bound)) then
find_roots = x
return
end if
end do
!Otherwise, two imaginary roots and one real root, return real root
else
Au = -sign(1.D0, R)*(abs(R)+sqrt(R**2-Q**3))**(1.D0/3.D0)
if (Au.eq.0.D0) then
Bu = 0.D0
else
Bu = Q/Au
end if
find_roots = (Au+Bu)-a/3.D0
return
end if
end function find_roots
Now it turns out that it can be shown analytically that a cubic equation with the following inputs:
Q0 = 1.D0
alpha = 1.D-2
dt = 0.00001D0
Y = 1000000.D0
find_roots(-(2.D0*Q0+Y), &
-(alpha-Q0**2-2.D0*Y*Q0+dt/2.D0*alpha), &
(dt/2.D0*alpha*Q0+Y*alpha-Y*Q0**2), &
Q0-sqrt(alpha), &
Q0+sqrt(alpha)))
MUST have a root between Q0+sqrt(alpha) and Q0-sqrt(alpha). This is a mathematical certainty. However, the function as called above will return 0, not the correct root, due to floating-point error, since the required result is very close to Q0+sqrt(alpha). I've confirmed this by creating a new function which uses quadruple precision. Unfortunately, I can't just always use quadruple precision since this function will be called billions of times and is a performance bottleneck.
So my question is, are there any general ways I could re-write this code to reduce these precision errors, while also maintaining the performance? I tried using the algorithm suggested by wikipedia, but the problem actually got worse.
https://www.cliffsnotes.com/study-guides/algebra/algebra-ii/factoring-polynomials/sum-or-difference-of-cubes
This should reduce rounding error.
Likewise, you should be able to find a much better grouping of terms, where you don't make the compiler guess what you want,
https://en.wikipedia.org/wiki/Horner%27s_method
alpha-Q0**2-2.D0*Y*Q0+dt/2.D0*alpha /= (alpha+alpha*.5*dt)-Q0*(Q0+2*Y)
You might argue that any good optimizer should know what to do with .5dt vs. dt/2. ifort considers that a part of -no-prec-div even though it can't change roundoff.
It's up to you whether you choose single precision constants for readability after checking to make sure that the promotion rules cause them to promote exactly to double. It seems particularly bad style to depend on f77 D0 suffix to choose the same data type as the never-standard real*8; no doubt it does if your compiler doesn't complain.
There is something wrong with the accuracy of your calculations, either the calculation of a,b,c or the find_roots function estimates.
I used the a,b,c that are calculated and found that your lower_bound and upper_bound were better estimates of the roots.
I then modified the bounds to be +/- sqrt(alpha)*1.1 so that the range test would work for 64-bit.
I also simplified constants that promote exactly to double.
Finally I compared your estimate of the root to the fn (0.9d0) and fn (1.1d0), which shows the find_roots function does not work for the a,b,c provided.
You should check your references for the error or it may just be the approach fails when acos (+/- 1.0 ) is used.
The program I used to test this with lots of prints is:
real*8 function find_roots (a, b, c, lower_bound, upper_bound)
implicit none
real*8, intent(in) :: a, b, c, lower_bound, upper_bound
real*8 :: Q, R, theta, x, Au, Bu, thi
integer :: i, iter
real*8 :: two_pi ! = 8 * atan (1.0d0)
Q = (a**2 - 3.*b)/9.
R = (2.*a**3 - 9.*a*b + 27.*c)/54.
two_pi = 8 * atan (1.0d0)
!If roots are all real, get root in range
if (R**2 < Q**3) then
iter = 0
x = R/sqrt(Q**3)
theta = acos(x)
print *, "theta = ", theta, x
do i=-1,1
iter = iter+1
!! x = -2.D0*sqrt(Q)* cos((theta + dble(i)*PI*2.D0)/3.D0) - a/3.D0
thi = (theta + i*two_pi)/3.
x = -2.*sqrt(Q) * cos (thi) - a/3.
!print *, "iter = ", iter, "root = ", x
if ( (x >= lower_bound) .and. (x <= upper_bound) ) then
find_roots = x
print *, "find_roots = ", x
! return
end if
end do
!Otherwise, two imaginary roots and one real root, return real root
else
Au = -sign(1.D0, R)*(abs(R)+sqrt(R**2-Q**3))**(1.D0/3.D0)
if (Au.eq.0.D0) then
Bu = 0.D0
else
Bu = Q/Au
end if
find_roots = (Au+Bu)-a/3.D0
return
end if
end function find_roots
real*8 function get_cubic (x, a, b, c)
implicit none
real*8, intent(in) :: x, a, b, c
get_cubic = ( ( x + a) * x + b ) * x + c
end function get_cubic
! Now it turns out that it can be shown analytically that a cubic equation with the following inputs:
real*8 Q0, alpha, dt, Y, a, b, c, lower_bound, upper_bound, val, fn
real*8, external :: find_roots, get_cubic
!
Q0 = 1.D0
alpha = 1.0D-2
dt = 0.00001D0
Y = 1000000.0D0
!
a = -(2.*Q0 + Y)
b = -(alpha - Q0**2 - 2.*Y*Q0 + dt/2.*alpha)
c = (dt/2.*alpha*Q0 + Y*alpha - Y*Q0**2)
write (*,*) a,b,c
!
lower_bound = Q0-sqrt(alpha)*1.1
upper_bound = Q0+sqrt(alpha)*1.1
write (*,*) lower_bound, upper_bound
!
val = find_roots (a, b, c, lower_bound, upper_bound)
!
fn = get_cubic ( val, a,b,c )
write (*,*) val, fn
!
! Test the better root values
val = 0.9d0
fn = get_cubic ( val, a,b,c )
write (*,*) val, fn
!
val = 1.1d0
fn = get_cubic ( val, a,b,c )
write (*,*) val, fn
end

Unclassifiable statement at (1) when calling a function

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

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