BlyxDocumentation
Browse chapters
Documentation / Numerical programming

Vectors and reductions

Represent several readings in one value and combine them into a weighted mean.

Choose a representation

A vector literal such as [5.0, 7.0, 9.0] holds numeric elements in order. Element storage is f64, including when the literal contains whole numbers. A vector can be empty. Bind it to a name or pass it to a function whose parameter type is vector.

Read by position

Indices begin at zero. For these three readings, len(readings) is 3 and at(readings, 2) is 9. Use an integer index and keep it below the length. The release supports reading vector elements. Build an accumulator when you need to calculate a derived result.

Give one reading extra weight

A dot product multiplies pairs at matching positions and adds them. With weights [1.0, 1.0, 2.0], the weighted total is 5 + 7 + 18 = 30. The total weight is 4. Dividing produces 7.5, which is closer to the final reading than the ordinary mean.

State the input contract

dot requires equal vector lengths. For a weighted average with nonnegative weights, require a positive total weight. An empty pair can have a valid dot product of zero while its mean has a zero denominator. Decide how your program should handle that case before you divide.

Try the program

Output Ready
Expected output
7.5
Open in the full playground →

Practice

Give the first reading double weight and give each of the others weight one.

Hint

Keep the number of weights equal to the number of readings.

Worked solution

The weighted total becomes 10 + 7 + 9 = 26. Divide by four to get 6.5.

Find

[1.0, 1.0, 2.0]

Replace with

[2.0, 1.0, 1.0]

Output after the change

6.5