Shop OBEX P1 Docs P2 Docs Learn Events
Average value in variable array? — Parallax Forums

Average value in variable array?

lardomlardom Posts: 1,659
edited 2013-04-06 10:28 in Propeller 1
What is the syntax in Spin for calculating the average value in a variable array? (If you can only add one element at a time a block of code could get really large).

Comments

  • JonnyMacJonnyMac Posts: 9,108
    edited 2013-04-05 21:24
    Is this a trick question or am I missing something?
    pub average(p_array, elements) | acc
    
      acc := 0                                                      ' clear accumulator
    
      repeat elements                                               ' total all
        acc += long[p_array]                                        ' get one
        p_array += 4                                                ' point to next element
    
      return acc / elements                                         ' return average
    


    If memory serves me, Phil (PhiPi) had some code to do a running average posted a while back -- you might want to do a search for that.
  • Mike GreenMike Green Posts: 23,101
    edited 2013-04-05 21:25
    You use a loop to add all the elements into a temporary variable, then divide by the number of elements like
    var long average, i, array[ n ]
    ' ...
    average := 0
    repeat i from 0 to n-1
       average += array[ i ]
    average /= n
    
  • lardomlardom Posts: 1,659
    edited 2013-04-05 22:09
    @JonnyMac, it's not a trick question. Thanks for the compliment and the code. I was just studying the "PUB Average" method of an 'ADC' object because what I was thinking would have filled two pages.
    @Mike Green, Thanks.
  • lardomlardom Posts: 1,659
    edited 2013-04-06 10:28
    Mike and JonnyMac, thanks again. I haven't tested this but the logic makes sense to me. I'm working on a 'bi-parented, child controlled autonomous navigation robot'. This piece of code has to find the widest path with a servo/ping combination that scans 180° in 20° increments.
    VAR
        long AveDistance[6], PingDistance[9], Wide_Path, Rotate_Amount
    
    PUB Find_Corridor  | i, j   
    
        i:= 0
        repeat j from 1 to 6
          repeat 4
            AveDistance[j]+= PingDistance[i]
            i++
          AveDistance[j]/= 4
          i-= 2
       
        repeat j from 1 to 6                    
          if AveDistance[j] > Wide_Path
            Wide_Path := AveDistance[j]
            Rotate_Amount := j
    
Sign In or Register to comment.