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
  1. 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]x
  2. y ← [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]y
  3. d ← 32.0

    6y = [4.0, 5.0, 6.0]7d = dot_product(x, y)8print '(F0.1)', d
    values this step32.0d[1.0, 2.0, 3.0]x[4.0, 5.0, 6.0]y
  4. print '(F0.1)', d

    7    d = dot_product(x, y)8    print '(F0.1)', d9end program dot_product_demo
    output32.0
    values this step32.0d

Follow the Products

  1. x is [1.0, 2.0, 3.0].
  2. y is [4.0, 5.0, 6.0].
  3. dot_product multiplies matching positions.
  4. The products are 4.0, 10.0, and 18.0.
  5. The sum is 32.0, so the program prints 32.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.