﻿using System;

namespace Corelicious.Statistics {
    public class LinearTrend {
        private Double _sumXY, _sumX, _sumXPow, _sumY, _n;

        /// <summary>
        ///   (n∑(xy)−∑x∑y) / (n∑x^2−(∑x)^2)
        /// </summary>
        public Double? Slope {
            get {
                if (_n == 0)
                    return null;

                var numerator = _n * _sumXY - _sumX * _sumY;
                var denumerator = _n * _sumXPow - _sumX * _sumX;
                if (denumerator == 0)
                    return 0;

                return numerator / denumerator;
            }
        }

        /// <summary>
        ///   (∑y−α∑x) / n
        /// </summary>
        public Double? Offset {
            get {
                if (_n == 0)
                    return null;

                return (_sumY - Slope.Value*_sumX)/_n;
            }
        }

        public virtual void Add(Double x, Double y) {
            _sumXY += (x * y);
            _sumX += x;
            _sumXPow += (x * x);
            _sumY += y;
            _n++;
        }
    }
}
