Fortran/Fortran Simple math

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Part of the Fortran WikiBook

Fortran has the following arithmetic operators:

+ addition
- subtraction
* multiplication
/ division
** exponentiation (associates right-to-left)

Here are some examples of their use:

i = 2 + 3   ! sets i equal to 5
i = 2 * 3   ! sets i equal to 6
i = 2 / 3   ! sets i equal to 0, since 2/3 is rounded down to the integer 0, see mixed mode
x = 2 / 3.0 ! sets x approximately equal to 2/3 or 0.666667
i = 2 ** 3  ! sets i equal to 2*2*2 = 8


Fortran has a wide range of functions useful in numerical work, such as sin, exp, and log. The argument of a function must have the proper type, and it is enclosed in parentheses:

x = sin(3.14159) ! sets x equal to sin(pi), which is zero


The intrinsic math functions of Fortran are elemental, meaning that they can take arrays as well as scalars as arguments and return a scalar or an array of the same shape:

real :: x(2),pi=3.14159
x = sin((/pi,pi/2/))


The above program fragment sets the two elements of array x, x(1) and x(2), equal to sin(pi) and sin(pi/2) respectively.