- Home /
get the average of a bunch of floats
I'm trying to write a function that calibrates the player movement script and what I'm trying to do is the following.
Run a script for lets say 2 seconds. And collect all the move speeds that happen in that 1 second.
My question about this part is how should I store these numbers because I can see a fair few being stored in 2 seconds. Should I use an array?
Next once the script is done I need to cycle through the results and get the average. Is there an easy way to do this?
Answer by Owen-Reynolds · Mar 30, 2011 at 04:41 AM
If you just want the average, just set Count=0; Sum=0;
. Each tick add Count++; Sum+=speed;
and say Avg=Speed/Count;
at the end. No need to store all the data.
I was assu$$anonymous$$g the OP needed to store the data anyway, for other reasons. Nevertheless, up-vote for a good observation :) (If there isn't any other need for the data, your way is definitely better.)
Answer by Jesse Anders · Mar 30, 2011 at 04:26 AM
You should be able to use a container of some sort (e.g. an array or List) to store the data. (A couple of seconds of sampling should only produce a few hundred samples at most, I'd guess.)
For averaging, there might be something in the .NET library, but I'm not sure off the top of my head. The procedure for averaging a set of values is straightforward though. Pseudocode:
sum = 0
for each value in values
sum += value
sum /= number of values
Your answer
![](https://koobas.hobune.stream/wayback/20220613115652im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Average of Normals 1 Answer
Generic List , average directional vector 1 Answer
Is it possible to simplify a 3D looped curve? 0 Answers
Frames Per Second 2 Answers
Compare Vector3 3 Answers