Problem averaging an (euler)angle

I’m trying to average number (i) of measurements of a euler angle by:

average = (average*i + measurement) / (i+1)

(and then i++ afterwards)

This goes well, except when sometimes the measurement is 359 and sometimes it is 1 degree, then it screws up the average measurement and my object starts to slowly spin.

How can I avoid this? Or is this a Quaternion job?

simply use Quaternions.

Averaging multiple quaternions using slerp shouldn’t be too difficult a task. and it avoids the wrapping issue

public static class QuaternionExtensions
{
    public static Quaternion Average(this Quaternion[] quaternions)
    {
        if(quaternions == null || quaternions.length < 1)
            return Quaternion.Identity;

        if(quaternions.length < 2)
            return quaternions[0];

        int count = quaternions.length;
        float weight = 1.0f / (float)count;
        Quaternion avg = Quaternion.Identity;

        for(int i=0; i<count; i++)
            avg *= Quaternion.Slerp(Quaternion.Identity, quaternions[i], weight);

        return avg;
    }
}

This code is likely not the fastest way to calculate it but it should be accurate without diving deep into Quaternion math.