User Tools

Site Tools


finding_sum_mod_partial_array

Finding the SUM or MOD of a partial array

by Richard Russell, January 2023

The SUM() and MOD() functions return the sum and modulus (square-root of the sum of the squares) respectively of a numeric array, and they are much faster than performing the calculations yourself in a loop. However you have no control over which elements are operated on: it is always the entire array (remember that in BBC BASIC array indices are zero-based).

To find the sum or modulus of a subset of the elements you can use the user-defined functions below. To illustrate their use, this code calculates the Standard Deviation of elements 1 to 8 inclusive of an array:

      DIM array(9)
      array() = 1,2,3,4,5,6,7,8,9,10
      mean = FNsum(array(),1,8) / 8
      array() -= mean
      PRINT FNmod(array(),1,8) / SQR(8)
      array() += mean

This prints 2.29128785, being the Standard Deviation of the values 2, 3, 4, 5, 6, 7, 8 and 9.

Here are the functions; the parameters are the array, the index of the first element to include, and the total number of elements over which to perform the operation. Please be aware that the array is temporarily modified, so do not access it in a timer interrupt or other asynchronous event handler:

      DEF FNsum(a(), I%, N%)
      IF DIM(a())<>1 ERROR 0, "Array must be one-dimensional"
      IF I% < 0 OR N% < 1 OR I% + N% - 1 > DIM(a(),1) ERROR 0, "Invalid array limits"
      LOCAL p%% : p%% = ^a(I%) - 5 
      LOCAL ?p%%, p%%!1 : ?p%% = 1 : p%%!1 = N% : PTR(a()) = p%%
      = SUM(a())
 
      DEF FNmod(a(), I%, N%)
      IF DIM(a())<>1 ERROR 0, "Array must be one-dimensional"
      IF I% < 0 OR N% < 1 OR I% + N% - 1 > DIM(a(),1) ERROR 0, "Invalid array limits"
      LOCAL p%% : p%% = ^a(I%) - 5
      LOCAL ?p%%, p%%!1 : ?p%% = 1 : p%%!1 = N% : PTR(a()) = p%%
      = MOD(a())

In a speed-critical application you may choose to omit the error-checking statements if you are sure that the parameters are valid.

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
finding_sum_mod_partial_array.txt · Last modified: 2024/01/05 00:21 by 127.0.0.1