We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Average of array
Page Index Toggle Pages: 1
Average of array (Read 650 times)
Average of array
Dec 6th, 2005, 4:42pm
Is there a quick way to find the average of all the elements in an array?  I thought this would be simple, but I can't seem to figure it out.
Re: Average of array
Reply #1 - Dec 6th, 2005, 7:31pm
This should do it:

float[] array;

// Initializing here... not part of the average computation
array = new float[1000];
for ( int i = 0; i < array.length; ++i )
 array[i] = random( -1, 1 );

// This is where we compute the average
float average = 0;
for ( int i = 0; i < array.length; ++i )
 average += array[i];
average /= (float)(array.length);

// The average should be close to zero
println( average );
Page Index Toggle Pages: 1