Part 5. A math program

(c) 2017 by Barton Paul Levenson



This program finds the area of a circle, given the circle's radius:


! Program to find the area of a circle.
program circle
    implicit none
    integer, parameter :: d  = selected_real_kind(p = 15)
    real(d), parameter :: pi = 3.141592653589793d0

    real(d)       :: area, radius	! Of the circle.
    character(80) :: units			! Linear units used.

    write (*, 10)
10  format('What radius is the circle?  =>', $)
    read  (*, *) radius

    write (*, 20)
20  format('What units is that in?      =>', $)
    read  (*, *) units

    area = pi * radius ** 2d0

    write (*, 30) area, trim(units)
30  format('The area is ', f10.5, ' square ', a, '.')
end program circle


Here's a typical console session:



Note the following points:

1. The asterisk ( * ) is used for multiplication in the assignment statement. The simple math operators are:


symbolmeaningexample
**
raise to a powerr ** 2 means r2
*
multiply3 * 4  means 3 x 4
/
divide2 / 3  means 2 ÷ 3
+
add1 + 2  means 1 + 2, duh
-
subtract4 - 3  means 4 - 3

If I had written the squaring code as radius ** 2 instead of radius ** 2d0, the compiler would have treated it as radius * radius, which is faster. Remember to use integer powers where you can.

2. The format specifier for double-precision numbers is f (or F; case doesn't matter). It is followed by two fields separated by a period. The first value gives the field length, the second the number of decimal places. Thus, in our program, the area of the circle is printed out in a field ten characters wide, with five digits after the decimal. If we had wanted scientific notation (with a base-ten exponent) for very large or very small values, the format descriptor to use would have been es rather than f.

In writing math expressions, you can override operator precedence with parentheses. Consider these assignment statements:


	x = 5 * (1 + 4)		! Assigns 25 to x.
	x = 5 * 1 + 4		! Assigns 9 to x.


With the "precedence hierarchy" in Fortran, exponentiation is performed first, then multiplication and division, and then addition and subtraction, other things being equal. The math operators also have "associativity." This just means that for several in a row, exponentiation is done right to left, while the others work from left to right. But to make the code clear for anyone who might read it later, it's better to use parentheses, even if they're not strictly necessary to the operation. Thus the second statement above would be better coded as:


    x = (5 * 1) + 4		! Assigns 9 to x.





Page created:05/05/2017
Last modified:  05/05/2017
Author:BPL