Normalising Randomness

Hi,

What I’m trying to do should be fairly simple, but for some reason I can’t get it to work. Assuming you have some kind of noisy/random signal, I want to be able to smooth that signal out by taking an average of the last (10…20 or however many) samples. I wrote something in Processing (simplified Java) a few months ago that did it just fine, but while trying to translate it into Unity I can’t get it working. Arrays don’t seem to work in the same way. Here is the code:

var randomness : float = 0.1;						//Amount of randomness of box move
var randomBox : Transform;							//The box to be moved randomly
var normalisedSphere : Transform;					//The sphere to show normalisation

private var xArray = new Array();					//Array for cataloging x position of random box
var numberOfSteps : int = 10;						//Number of samples for normalisation
private var preMult : float;						//Total before normalisation

function Start() {									//Initialise array as empty
	for(var k : int = 0; k<numberOfSteps; k++){
	xArray[k] = 0;
	}
}

function Update () {
	randomBox.transform.position.x += Random.Range(-randomness,randomness);		//Move box to random position

xArray[0] = randomBox.transform.position.x;					//Place current position into first place of array every frame
for(var i : int = numberOfSteps; i > 0; i--){					//Shift every position in array along one (so xArray[0] is moved to xArray[1] etc.
	xArray[i] = xArray[i-1];
	}
	
Debug.Log(xArray);								//Print array of last (numberOfSteps) positions
preMult = 0;								        //Reset total to zero

for(var j : int = 0; j<numberOfSteps-1; j++){			//Add last (numberOfSteps) positions together as preMult variable
	preMult+=xArray[j];
	}
var

The debug line which prints the array always prints the current x value followed by a string of zeros, so the for loop which is supposed to move everything along one in the array doesn’t seem to work but I don’t know why since the exact same bit of code works for me in Processing.
I should say that what I’m actually trying to do is figure out a way to smooth the shakiness of the Kinect signal. If anyone knows of any way to do this nicely it would be massively appreciated! It would be significantly smoothed if I could just figure out a way to strip a number with ten decimal places down to a number of 3 or 4 decimal places - is this possible? For example, to transform 10.434783245 into 10.43
I’ve looked around and can’t see a way to do this.
Any other suggestions for smoothing the Kinect movement (which I’m using for headtracking) would be much appreciated!
Sorry for being such a rookie, and thank you all!
Regards,
S

I don’t know JS but in C# this would be easy with a Math.Round or Math.Truncate. Seems like your overcomplicating the problem using arrays.

Math.Round(randomBox.transform.position.x, 3)

Math.Truncate(randomBox.transform.position.x * 1000) / 1000;

Sounds like a cool project tho.