Finding the modulus of part of an array
by Richard Russell, October 2013
The MOD() function, when applied to an array, returns the square-root of the sum of the squares of the elements of the array (the so-called modulus). It may occasionally be useful to discover the modulus of only part of an array, but BBC BASIC doesn't have a built-in function to do that.
Of course it's straightforward to find the modulus using a loop:
totalsq = 0 FOR index% = first% TO last% totalsq += array(index%)^2 NEXT Modulus = SQR(totalsq)
where first% and last% define the range of indices (inclusive) over which the modulus should be calculated.
However this approach is relatively slow, especially if the number of elements included is large, and it would be desirable to have a faster method. Fortunately there is a way, although the code isn't very nice:
DEF FN_ModPartialArray(d(), first%, last%) LOCAL i%% i%% = ^d(first%)-5 LOCAL ?i%%, i%%!1, a() ?i%% = 1 : i%%!1 = last%-first%+1 PTR(a()) = i%% = MOD(a())
The array a() must be the same type (i.e. have the same suffix character, if any) as the array whose modulus is being calculated.
Note that during execution of the function the array contents are temporarily changed, so don't use this method if your program has a timer interrupt in which the array is accessed.
If errors are trapped (using ON ERROR) and you need your program to resume execution after an error (e.g. pressing the Escape key), add a statement to ensure the array contents are restored:
DEF FN_ModPartialArray(d(), first%, last%) LOCAL i%% i%% = ^d(first%)-5 LOCAL ?i%%, i%%!1, a() ON ERROR LOCAL RESTORE LOCAL : ERROR ERR, REPORT$ ?i%% = 1 : i%%!1 = last%-first%+1 PTR(a()) = i%% = MOD(a())