C# Decimal Math helpers

Here are some helpers I put together for using decimal with my technical indicators.

    
    public static class Maths
    {
        public const decimal Zero = 0.0M;
        public const decimal One = 1.0M;
        private const decimal Half = 0.5M;
        private const decimal Einv = 0.3678794411714423215955237701614608674458111310317678M;
        public const decimal E = 2.7182818284590452353602874713526624977572470936999595749M;
        private const int MaxIteration = 100;
 
        public static decimal Divide(decimal divisor, decimal dividend)
        {
            if (divisor == 0 || dividend == 0)
                return 0;

            return divisor / dividend;
        }

        public static decimal Normalize(decimal input)
        {
            return input > .99m ? .999m : input < -.99m ? -.999m : input;
        }

        // source : https://github.com/raminrahimzada/CSharp-Helper-Classes/blob/master/Math/DecimalMath/DecimalMath.cs#L211
        public static decimal Log(decimal x)
        {
            if (x <= Zero)
            {
                throw new ArgumentException("x must be greater than zero");
            }
            var count = 0;
            while (x >= One)
            {
                x *= Einv;
                count++;
            }
            while (x <= Einv)
            {
                x *= E;
                count--;
            }
            x--;
            if (x == 0) return count;
            var result = Zero;
            var iteration = 0;
            var y = One;
            var cacheResult = result - One;
            while (cacheResult != result && iteration < MaxIteration)
            {
                iteration++;
                cacheResult = result;
                y *= -x;
                result += y / iteration;
            }
            return count - result;
        }
    }
    
In Tags , ,