Practical Fortran
Dot Product
Built-in Reduction
dot_product multiplies two same-shape arrays element-wise and sums the result.
Program
Play the program to compute the dot product of two real vectors.
dot_product.f90
Replay: real traced execution (multi-file project)
program dot_product_demo
implicit none
real :: x(3), y(3)
real :: d
x = [1.0, 2.0, 3.0]
y = [4.0, 5.0, 6.0]
d = dot_product(x, y)
print '(F0.1)', d
end program dot_product_demo
x ← [1.0, 2.0, 3.0]
4real :: d5x = [1.0, 2.0, 3.0]6y = [4.0, 5.0, 6.0]values this step[1.0, 2.0, 3.0]xy ← [4.0, 5.0, 6.0]
5x = [1.0, 2.0, 3.0]6y = [4.0, 5.0, 6.0]7d = dot_product(x, y)values this step[4.0, 5.0, 6.0]yd ← 32.0
6y = [4.0, 5.0, 6.0]7d = dot_product(x, y)8print '(F0.1)', dvalues this step32.0d[1.0, 2.0, 3.0]x[4.0, 5.0, 6.0]yprint '(F0.1)', d
7 d = dot_product(x, y)8 print '(F0.1)', d9end program dot_product_demooutput32.0values this step32.0d
Follow the Products
xis[1.0, 2.0, 3.0].yis[4.0, 5.0, 6.0].dot_productmultiplies matching positions.- The products are
4.0,10.0, and18.0. - The sum is
32.0, so the program prints32.0. | x value | y value | product | | --- | --- | --- | | 1.0 | 4.0 | 4.0 | | 2.0 | 5.0 | 10.0 | | 3.0 | 6.0 | 18.0 | | total | - | 32.0 |
dot_product
`dot_product(x, y)` returns `sum(x * y)` for vectors.
real array
`real :: x(3)` declares a length-3 real vector.
F0.1
`F0.1` prints a real with one decimal and no extra width.
Exercise: dot_product.f90
Reproduce 32.0, then trace the three products 1*4, 2*5, and 3*6 that add to 32.0.