// HalfSquared Euclidean Distance
        private double CalculateError(IMultilayerNeuralNetwork network, double[] expectedOutput)
        {
            double error       = 0;
            int    layersCount = network.Layers.Length;

            IActivationFunction function = network.Layers[0].Neurons[0].ActivationFunction;

            ILayer layer = network.Layers.Last();

            double[] errors = neuronErrors.Last();

            for (int i = 0, n = layer.Neurons.Length; i < n; i++)
            {
                double output = layer.Neurons[i].Output;
                double e      = expectedOutput[i] - output;
                errors[i] = e * function.ComputeDerivative2(output);
                error    += (e * e);
            }

            for (int j = layersCount - 2; j >= 0; j--)
            {
                layer = network.Layers[j];
                ILayer layerNext = network.Layers[j + 1];
                errors = neuronErrors[j];
                double[] errorsNext = neuronErrors[j + 1];

                for (int i = 0, n = layer.Neurons.Length; i < n; i++)
                {
                    var sum = 0.0;
                    for (int k = 0; k < layerNext.Neurons.Length; k++)
                    {
                        sum += errorsNext[k] * layerNext.Neurons[k].Weights[i];
                    }

                    errors[i] = sum * function.ComputeDerivative2(layer.Neurons[i].Output);
                }
            }

            return(error / 2.0);
        }