How to Implement the Bisection Method Algorithm in Fortran 90
Program For Bisection Method In Fortran
If you are looking for a simple and reliable way to find the roots of a nonlinear equation, you may want to try the bisection method. The bisection method is a numerical technique that applies to any continuous function that changes sign over an interval. It works by repeatedly dividing the interval into two halves and selecting the one that contains the root.
Program For Bisection Method In Fortran
Download Zip: https://www.google.com/url?q=https%3A%2F%2Furluso.com%2F2ulp0E&sa=D&sntz=1&usg=AOvVaw1UhebOX7a4XlP-qPva_82y
One of the best programming languages to implement the bisection method is Fortran. Fortran is a general-purpose, compiled, imperative language that is especially suited for numeric computation and scientific computing. Fortran has been around since 1957 and has evolved over time to incorporate modern features such as array operations, object-oriented programming, parallel processing, and more.
In this article, you will learn how to write a program for bisection method in Fortran. You will also learn some basic concepts of Fortran programming and how to improve your program for better performance and usability. By the end of this article, you will be able to solve any nonlinear equation using Fortran and the bisection method.
The bisection method algorithm
The bisection method is based on a simple idea: if a continuous function f(x) changes sign over an interval [a,b], then there must be at least one root in that interval. The algorithm works as follows:
Choose an initial interval [a,b] such that f(a) and f(b) have opposite signs.
Calculate the midpoint c = (a+b)/2 and evaluate f(c).
If f(c) = 0, then c is a root and the algorithm stops.
If f(c) has the same sign as f(a), then replace a with c and repeat from step 2.
If f(c) has the same sign as f(b), then replace b with c and repeat from step 2.
The algorithm converges to a root as long as the function is continuous and has only one root in the interval. The rate of convergence is linear, which means that the error is reduced by half at each iteration. The algorithm stops when the interval is sufficiently small or when a predefined number of iterations is reached.
For example, suppose we want to find a root of the equation x - x - 2 = 0. We can choose an initial interval [1,2] since f(1) = -2 0. The following table shows the first five iterations of the bisection method:
Iterationabcf(a)f(b)f(c)
1121.5-240.125
21.521.750.12541.609
31.51.751.6250.1251.6090.666
41.6251.751.6875<
0.666<
1.6090.912
5
1.6875
1.75 <
1.7188 <
0.912 <
1.609 <
1.198 <
/tr>
/table>
We can see that the interval is getting smaller and the value of f(c) is getting closer to zero. The root is approximately 1.7188 after five iterations.
The pseudocode of the bisection method is as follows:
function bisection(f, a, b, tol, maxiter) // f is the function to be solved // a and b are the initial interval endpoints // tol is the tolerance for the interval size // maxiter is the maximum number of iterations // check if f(a) and f(b) have opposite signs if f(a) * f(b) > 0 then return "Error: f(a) and f(b) must have opposite signs" end if // initialize the iteration counter iter = 0 // repeat until the interval is small enough or the maximum number of iterations is reached repeat // increment the iteration counter iter = iter + 1 // calculate the midpoint and evaluate f(c) c = (a + b) / 2 fc = f(c) // check if c is a root or the interval is small enough if fc = 0 or (b - a)
The Fortran programming language
Fortran is one of the oldest and most widely used programming languages for scientific and engineering applications. The name Fortran stands for FORmula TRANslation, as it was designed to allow easy translation of mathematical formulas into executable code.
Fortran has gone through several revisions and extensions over the years, from Fortran I in 1957 to Fortran 2018 in 2018. The most popular versions are Fortran 77, Fortran 90, Fortran 95, Fortran 2003, and Fortran 2008. Each version introduced new features and improved compatibility with other languages and platforms.
Some of the main features of Fortran are:
It is a compiled language, which means that it requires a compiler to translate the source code into executable code.
It is an imperative language, which means that it specifies the sequence of instructions to perform a task.
It supports both procedural and object-oriented programming paradigms, which means that it allows defining functions, subroutines, modules, classes, and objects.
It supports array operations, which means that it allows performing arithmetic and logical operations on entire arrays without using loops.
It supports parallel processing, which means that it allows running multiple tasks simultaneously on multiple processors or cores.
It has a rich set of intrinsic functions and libraries for mathematical, statistical, scientific, and engineering computations.
It has a simple and consistent syntax, which means that it has a few keywords and rules for writing statements.
It has high performance and portability, which means that it can run fast and efficiently on various platforms and architectures .
The basic syntax and data types of Fortran are as follows:
A Fortran program consists of one or more program units, such as main programs, functions, subroutines, modules, and blocks.
A program unit begins with a statement that specifies its name and type, such as PROGRAM, FUNCTION, SUBROUTINE, MODULE, or BLOCK.
A program unit ends with an END statement that may optionally include the name and type of the program unit.
A statement is a line of code that performs an action or defines a variable, constant, or expression.
A statement can be continued on the next line by using an ampersand (&) at the end of the first line and at the beginning of the second line.
A comment is a line of code that is ignored by the compiler and is used to explain or document the program. A comment begins with an exclamation mark (!) and can be placed anywhere in a line except within a character string.
A variable is a name that represents a value that can change during the execution of the program. A variable must be declared before it is used, either implicitly or explicitly.
An implicit declaration means that the type and attributes of a variable are determined by the first letter of its name, according to the implicit typing rules. For example, a variable that begins with I, J, K, L, M, or N is assumed to be an integer, while any other letter is assumed to be a real.
An explicit declaration means that the type and attributes of a variable are specified by using a type declaration statement, such as INTEGER, REAL, COMPLEX, CHARACTER, LOGICAL, or TYPE. For example, INTEGER :: i, j declares two integer variables i and j.
A constant is a name that represents a fixed value that cannot change during the execution of the program. A constant can be either a literal constant or a named constant.
A literal constant is a value that is written directly in the code, such as 3.14, 'Hello', or .TRUE.. A literal constant has an implicit type based on its form and value.
A named constant is a variable that is assigned a value only once by using a parameter attribute in its declaration. For example, REAL, PARAMETER :: pi = 3.14159 declares a real named constant pi with the value 3.14159.
An expression is a combination of variables, constants, operators, and functions that evaluates to a single value. An expression has a type and a value based on its components and the rules of precedence and associativity.
An operator is a symbol that performs an arithmetic, logical, relational, or bitwise operation on one or more operands. For example, +, -, *, /, , .AND., .OR., .NOT., .EQ., .NE., .LT., .GT., .LE., .GE., .EQV., .NEQV., etc.
A function is a program unit that takes one or more arguments and returns a single value. A function can be either intrinsic or user-defined.
An intrinsic function is a predefined function that is built into the language and performs a common operation. For example, SIN(x), COS(x), TAN(x), EXP(x), LOG(x), SQRT(x), ABS(x), MAX(x,y), MIN(x,y), etc.
A user-defined function is a function that is written by the programmer and performs a specific task. A user-defined function must have a FUNCTION statement at the beginning and an END FUNCTION statement at the end. It must also have an explicit or implicit return value.
- A subroutine is a program unit that performs a specific task and does not return a value. A subroutine can take zero or more arguments and modify them. A subroutine must have a SUBROUTINE statement at the beginning and an END SUBROUTINE statement at the end. It must also have an explicit or implicit interface.
How to write a program for bisection method in Fortran
Now that we have learned some basic concepts of Fortran, we can write a program for bisection method in Fortran. The program will consist of three parts: a main program, a function that defines the equation to be solved, and a subroutine that implements the bisection method.
The structure and logic of the program are as follows:
The main program will ask the user to enter the initial interval endpoints, the tolerance, and the maximum number of iterations. It will then call the subroutine bisection with these inputs and the function f as arguments. It will then print the result or the error message returned by the subroutine.
The function f will take a real argument x and return the value of f(x) = x - x - 2. This is the equation that we want to find a root of.
The subroutine bisection will take five arguments: f, a, b, tol, and maxiter. It will implement the bisection method algorithm as described above and return either the root and the number of iterations or an error message.
The code of the program with comments is as follows:
! Program for bisection method in Fortran PROGRAM bisect IMPLICIT NONE ! Declare variables REAL :: a, b, tol, root INTEGER :: maxiter, iter CHARACTER(LEN=80) :: msg ! Ask the user to enter the initial interval endpoints PRINT *, "Enter the initial interval endpoints (a,b):" READ *, a, b ! Ask the user to enter the tolerance PRINT *, "Enter the tolerance:" READ *, tol ! Ask the user to enter the maximum number of iterations PRINT *, "Enter the maximum number of iterations:" READ *, maxiter ! Call the subroutine bisection with these inputs and the function f as arguments CALL bisection(f, a, b, tol, maxiter, root, iter, msg) ! Print the result or the error message PRINT *, msg IF (msg == "Success") THEN PRINT *, "The root is:", root PRINT *, "The number of iterations is:", iter END IF END PROGRAM bisect ! Function that defines the equation to be solved FUNCTION f(x) IMPLICIT NONE ! Declare variables REAL :: f, x ! Calculate f(x) = x^3 - x - 2 f = x3 - x - 2 END FUNCTION f ! Subroutine that implements the bisection method SUBROUTINE bisection(f, a, b, tol, maxiter, root, iter, msg) IMPLICIT NONE ! Declare variables REAL :: f, a, b, tol, c, fc INTEGER :: maxiter, iter CHARACTER(LEN=80) :: msg ! Check if f(a) and f(b) have opposite signs IF (f(a) * f(b) > 0) THEN msg = "Error: f(a) and f(b) must have opposite signs" RETURN END IF ! Initialize the iteration counter iter = 0 ! Repeat until the interval is small enough or the maximum number of iterations is reached DO ! Increment the iteration counter iter = iter + 1 ! Calculate the midpoint and evaluate f(c) c = (a + b) / 2 fc = f(c) ! Check if c is a root or the interval is small enough IF (fc == 0 .OR. (b - a)
How to compile and run the program for bisection method in Fortran
To compile and run the program for bisection method in Fortran, you will need a Fortran compiler and a text editor. There are many Fortran compilers available, such as GNU Fortran, Intel Fortran, IBM XL Fortran, etc. You can also use an online compiler and IDE, such as Repl.it, JDoodle, OnlineGDB, etc.
For this example, we will use GNU Fortran and Repl.it. The steps are as follows:
Open Repl.it and select Fortran as the language.
Copy and paste the code of the program into the editor.
Click on the Run button to compile and execute the program.
Enter the inputs as prompted by the program and press Enter.
See the output displayed on the console.
The following screenshot shows an example of running the program with Repl.it:
We can see that the program successfully finds a root of the equation x - x - 2 = 0 in 20 iterations with a tolerance of 0.0001. The root is approximately 1.5214.
How to improve the program for bisection method in Fortran
The program for bisection method in Fortran that we have written is functional and correct, but it can be improved in several ways. Here are some suggestions to make the program more robust, efficient, and user-friendly:
Add error handling to catch any exceptions or invalid inputs that may occur during the execution of the program. For example, use a TRY-CATCH block to handle any errors that may arise from reading or writing files, performing arithmetic operations, or calling external functions or subroutines.
Add input validation to check if the inputs entered by the user are valid and within the expected range. For example, use an IF-THEN-ELSE block to check if the initial interval endpoints are real numbers, if they have opposite signs, if they are within the domain of the function, etc.
Add convergence criteria to stop the bisection method when a certain level of accuracy or precision is achieved. For example, use a DO-WHILE loop to repeat the bisection method until either the interval size or the function value at the midpoint is less than a specified threshold.
Add output formatting to display the results in a clear and readable way. For example, use WRITE statements with format specifiers to control the number of decimal places, alignment, spacing, etc. of the output values.
The following code shows how to implement these improvements in the program:
! Program for bisection method in Fortran with improvements PROGRAM bisect IMPLICIT NONE ! Declare variables REAL :: a, b, tol, root INTEGER :: maxiter, iter CHARACTER(LEN=80) :: msg ! Ask the user to enter the initial interval endpoints PRINT *, "Enter the initial interval endpoints (a,b):" READ *, a, b ! Validate the inputs IF (.NOT. (ISNAN(a) .OR. ISNAN(b))) THEN ! Check if a and b are real numbers IF (f(a) * f(b) > 0) THEN ! Check if f(a) and f(b) have opposite signs PRINT *, "Error: f(a) and f(b) must have opposite signs" STOP ! Terminate the program END IF ELSE PRINT *, "Error: a and b must be real numbers" STOP ! Terminate the program END IF ! Ask the user to enter the tolerance PRINT *, "Enter the tolerance:" READ *, tol ! Validate the input IF (.NOT. ISNAN(tol)) THEN ! Check if tol is a real number IF (tol = tol .AND. iter < maxiter) ! Increment the iteration counter iter = iter + 1 ! Calculate the midpoint and evaluate f(c) c = (a + b) / 2 fc = f(c) ! Check if c is a root or the interval is small enough IF (fc == 0 .OR. err < tol) THEN root = c ! Return the root msg = "Success" ! Return the success message RETURN ! Exit the subroutine END IF ! Update the interval based on the sign of f(c) IF (f(a) * fc < 0) THEN b = c ! Replace b with c if f(