Using the SUM Function in Fortran

Fortran is a high-level programming language widely used in scientific computing, numerical simulations, and engineering applications. One of its most powerful features is array operations, which allow programmers to perform calculations on multiple data points efficiently. Among these operations, the SUM function is a fundamental tool used to compute the total of all elements in an array.

This post provides a comprehensive discussion on the SUM function in Fortran, including syntax, examples with different data types, multi-dimensional arrays, logical arrays, advanced usage with array slicing, and best practices.

1. Introduction to the SUM Function

The SUM function is a built-in Fortran intrinsic function that computes the sum of elements in an array. It is highly efficient, concise, and avoids the need for explicit loops to compute totals.

Key points about SUM:

  • Can be applied to integer, real, double precision, and logical arrays
  • Operates on both one-dimensional and multi-dimensional arrays
  • Can include optional dimension and mask arguments for advanced usage
  • Reduces code complexity and improves readability

2. Syntax of SUM Function

The general syntax of the SUM function is:

result = sum(array [, dim] [, mask])
  • array: The array whose elements are to be summed
  • dim (optional): Specifies the dimension along which the sum is performed
  • mask (optional): Logical condition that determines which elements to include

2.1 Basic Syntax Example

real :: arr(5), total
arr = (/1, 2, 3, 4, 5/)
total = sum(arr)
print *, "Sum of elements:", total

Explanation:

  • arr is a one-dimensional real array
  • sum(arr) returns 15.0, the sum of all elements
  • Eliminates the need for an explicit loop

3. Using SUM with Integer Arrays

The SUM function works seamlessly with integer arrays:

integer :: numbers(10), total
numbers = (/1,2,3,4,5,6,7,8,9,10/)
total = sum(numbers)
print *, "Total sum:", total

Explanation:

  • The sum of numbers 1 through 10 is 55
  • SUM automatically determines the data type of the result based on the array type

3.1 SUM with Subset of Elements

You can sum a subset of array elements using array slicing:

integer :: numbers(10), total
numbers = (/1,2,3,4,5,6,7,8,9,10/)
total = sum(numbers(3:7))
print *, "Sum of elements 3 to 7:", total

Explanation:

  • numbers(3:7) selects elements 3 through 7
  • SUM returns 3+4+5+6+7 = 25

4. Using SUM with Real Arrays

Real arrays often represent measurements, scientific data, or simulation outputs. SUM simplifies aggregation:

real :: temperatures(5), total
temperatures = (/36.5, 37.0, 38.2, 36.8, 37.5/)
total = sum(temperatures)
print *, "Sum of temperatures:", total

Explanation:

  • Computes total temperature
  • Useful for calculating averages and other aggregate statistics

4.1 Calculating Average Using SUM

real :: temperatures(5), total, average
temperatures = (/36.5, 37.0, 38.2, 36.8, 37.5/)
total = sum(temperatures)
average = total / size(temperatures)
print *, "Average temperature:", average

Explanation:

  • SUM provides the numerator for the average calculation
  • size() returns the number of elements
  • Eliminates manual looping and reduces errors

5. SUM with Logical Arrays

SUM can also be used with logical arrays. In Fortran, .true. is treated as 1 and .false. as 0 when used in SUM:

logical :: flags(5)
integer :: total_true
flags = (/ .true., .false., .true., .true., .false. /)
total_true = sum(flags)
print *, "Number of true values:", total_true

Explanation:

  • SUM counts the number of .true. elements in the logical array
  • Efficient way to determine how many conditions are satisfied

6. SUM with Multi-Dimensional Arrays

SUM can operate on multi-dimensional arrays. By default, it sums all elements:

integer :: matrix(2,3), total
matrix = reshape((/1,2,3,4,5,6/), shape(matrix))
total = sum(matrix)
print *, "Sum of all matrix elements:", total

Explanation:

  • Reshape initializes a 2×3 matrix
  • SUM calculates 1+2+3+4+5+6 = 21
  • Works without explicit loops

6.1 SUM Along a Specific Dimension

integer :: matrix(2,3), sum_row, sum_col
matrix = reshape((/1,2,3,4,5,6/), shape(matrix))

sum_row = sum(matrix, dim=1)  ! Sum along rows (result is 1x3 array)
sum_col = sum(matrix, dim=2)  ! Sum along columns (result is 2x1 array)

print *, "Sum along rows:", sum_row
print *, "Sum along columns:", sum_col

Explanation:

  • dim=1 sums along the first dimension (rows)
  • dim=2 sums along the second dimension (columns)
  • Returns arrays with sums along the specified dimension

7. SUM with Mask Argument

The optional mask argument allows summing elements that satisfy a condition:

integer :: numbers(10), total_even
numbers = (/1,2,3,4,5,6,7,8,9,10/)
total_even = sum(numbers, mask = mod(numbers,2) == 0)
print *, "Sum of even numbers:", total_even

Explanation:

  • Mask selects only even numbers
  • SUM computes 2+4+6+8+10 = 30
  • Powerful tool for conditional aggregation

7.1 Mask with Logical Arrays

integer :: numbers(10), total_positive
numbers = (/-5,-3,0,2,4,6,8,10,12,14/)
total_positive = sum(numbers, mask = numbers > 0)
print *, "Sum of positive numbers:", total_positive

Explanation:

  • Only numbers greater than 0 are summed
  • Demonstrates advanced conditional selection with SUM

8. SUM in Loops vs SUM Function

Without SUM, you would need explicit loops:

integer :: numbers(5), i, total
numbers = (/1,2,3,4,5/)
total = 0
do i = 1, size(numbers)
total = total + numbers(i)
end do print *, "Total sum:", total

Using SUM:

total = sum(numbers)

Explanation:

  • SUM eliminates manual looping
  • Reduces code length and potential errors
  • Enhances readability

9. SUM with Arrays of Real Numbers and Precision

When dealing with real numbers, SUM can accumulate values in higher precision using kind parameters:

real(kind=8) :: arr(5), total
arr = (/1.1d0, 2.2d0, 3.3d0, 4.4d0, 5.5d0/)
total = sum(arr)
print *, "Total sum (double precision):", total

Explanation:

  • kind=8 ensures double precision
  • SUM respects the data type of the array elements
  • Important in scientific computations requiring high accuracy

10. SUM with Array Slicing

Fortran allows slicing arrays and applying SUM:

integer :: numbers(10), total_slice
numbers = (/1,2,3,4,5,6,7,8,9,10/)
total_slice = sum(numbers(3:8))
print *, "Sum of elements 3 to 8:", total_slice

Explanation:

  • Array slice numbers(3:8) selects a subset
  • SUM computes the sum of the slice efficiently

10.1 Step-wise Slicing

integer :: numbers(10), total_step
numbers = (/1,2,3,4,5,6,7,8,9,10/)
total_step = sum(numbers(1:10:2))
print *, "Sum of elements with step 2:", total_step

Explanation:

  • 1:10:2 selects elements 1,3,5,7,9
  • SUM adds only these selected elements

11. Practical Applications of SUM

  1. Calculating total scores in exams
  2. Aggregating measurement data in experiments
  3. Counting occurrences using logical arrays
  4. Computing totals in financial and engineering simulations
  5. Conditional sums using mask argument for data filtering

11.1 Example: Total Score of Students

integer :: scores(5), total_score
scores = (/85, 90, 78, 92, 88/)
total_score = sum(scores)
print *, "Total score of students:", total_score

Explanation:

  • Directly computes total score
  • More concise than loop-based summation

11.2 Example: Sum of Positive Measurements

real :: measurements(6), total_positive
measurements = (/ -1.2, 2.5, 0.0, 3.8, -0.5, 4.0 /)
total_positive = sum(measurements, mask = measurements > 0)
print *, "Sum of positive measurements:", total_positive

Explanation:

  • Mask selects only positive measurements
  • SUM provides total efficiently

11.3 Example: Counting True Flags Using SUM

logical :: flags(6)
integer :: count_true
flags = (/ .true., .false., .true., .true., .false., .true. /)
count_true = sum(flags)
print *, "Number of TRUE flags:", count_true

Explanation:

  • .true. elements are counted as 1
  • SUM computes total number of true flags directly

12. Best Practices for Using SUM

  1. Use SUM instead of loops for simple totals to improve readability.
  2. Use mask argument for conditional sums instead of filtering manually.
  3. Ensure correct data type to prevent overflow or precision loss.
  4. Combine with array slicing for partial sums.
  5. Use SUM with multi-dimensional arrays and dim argument for advanced data analysis.

13. Complete Example: SUM Function in Action

program sum_demo
implicit none
integer :: numbers(10), total_numbers, total_even
real :: temperatures(5), total_temp, avg_temp
logical :: flags(5)
integer :: total_true
integer :: i
! Integer array
numbers = (/1,2,3,4,5,6,7,8,9,10/)
total_numbers = sum(numbers)
print *, "Total sum of numbers:", total_numbers
! Sum of even numbers using mask
total_even = sum(numbers, mask = mod(numbers,2) == 0)
print *, "Sum of even numbers:", total_even
! Real array
temperatures = (/36.5, 37.0, 38.2, 36.8, 37.5/)
total_temp = sum(temperatures)
avg_temp = total_temp / size(temperatures)
print *, "Sum of temperatures:", total_temp
print *, "Average temperature:", avg_temp
! Logical array
flags = (/ .true., .false., .true., .false., .true. /)
total_true = sum(flags)
print *, "Number of TRUE flags:", total_true
! Array slicing
print *, "Sum of numbers 3 to 7:", sum(numbers(3:7))
! Step-wise slicing
print *, "Sum of numbers with step 2:", sum(numbers(1:10:2))
end program sum_demo

Explanation:

  • Demonstrates SUM with integer, real, and logical arrays
  • Shows usage of mask, slicing, step-wise selection
  • Computes totals and averages efficiently
  • Highlights practical use cases and best practices

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *