Exemple #1
0
        /// <summary>
        /// Normalize according to folowing rules
        ///   a) if there is a minus sign it will remain only in numerator
        ///   b) if there is common divisor, both numerator and denominator are divided by this common divisor
        /// </summary>
        /// <returns></returns>
        public Rational <T, TPolicy> Normalize()
        {
            if (Policy.IsOne(Denominator))
            {
                return(this);
            }

            if (Policy.IsZero(Numerator))
            {
                return(new Rational <T, TPolicy>(Policy.Zero(), Policy.One()));
            }

            var n = Numerator;
            var d = Denominator;

            if ((Policy.IsBelowZero(n) && Policy.IsBelowZero(d)) || Policy.IsBelowZero(d))
            {
                n = Policy.Negate(n);
                d = Policy.Negate(d);
            }

            var gcd = Policy.Gcd(Policy.Abs(n), d);

            if (!Policy.IsOne(gcd))
            {
                n = Policy.Div(n, gcd);
                d = Policy.Div(d, gcd);
            }
            return(new Rational <T, TPolicy>(n, d));
        }