User Tools

Site Tools


finding_sum_mod_partial_array

This is an old revision of the document!


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. Please be aware that they temporarily modify the array, 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())
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.1673020401.txt.gz · Last modified: 2024/01/05 00:16 (external edit)