Numerical Patterns
Weighted Average
Combine Values
A weighted average multiplies each value by its weight, sums the products, and divides by the total weight.
Program
Play the program to choose the third weight and watch the average change.
weighted_average.f90
program weighted_average_demo
implicit none
real :: values(3), weights(3)
real :: weighted_sum, weight_total, average
real :: third_weight
values = [10.0, 20.0, 30.0]
third_weight =
weights = [1.0, 2.0, third_weight]
weighted_sum = sum(values * weights)
weight_total = sum(weights)
average = weighted_sum / weight_total
print '(F0.1)', average
end program weighted_average_demo
program weighted_average_demo
implicit none
real :: values(3), weights(3)
real :: weighted_sum, weight_total, average
real :: third_weight
values = [10.0, 20.0, 30.0]
third_weight =
weights = [1.0, 2.0, third_weight]
weighted_sum = sum(values * weights)
weight_total = sum(weights)
average = weighted_sum / weight_total
print '(F0.1)', average
end program weighted_average_demo
program weighted_average_demo
implicit none
real :: values(3), weights(3)
real :: weighted_sum, weight_total, average
real :: third_weight
values = [10.0, 20.0, 30.0]
third_weight =
weights = [1.0, 2.0, third_weight]
weighted_sum = sum(values * weights)
weight_total = sum(weights)
average = weighted_sum / weight_total
print '(F0.1)', average
end program weighted_average_demo
array product
`values * weights` multiplies corresponding elements.
sum
`sum(...)` reduces an array expression to one scalar.
weighted average
Dividing by `sum(weights)` keeps the result on the original value scale.