码迷,mamicode.com
首页 > 其他好文 > 详细

定点数除法

时间:2017-02-11 19:06:49      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:数位   cti   pre   logs   bool   左移   ide   整数   ret   

        public static DFix FastDiv(DFix x, DFix y)
        {
            long xl = x.m_rawValue;
            long yl = y.m_rawValue;
            long result = 0;

            if (yl == 0)
            {
                throw new DivideByZeroException();
            }

            bool negative = ((xl >= 0) ^ (yl >= 0));        // 符号位
            ulong remainder = (ulong)(xl >= 0 ? xl : -xl);  // 余数,被除数
            ulong divider = (ulong)(yl >= 0 ? yl : -yl);    // 除数
            ulong quotient = remainder / divider;           // 商数,先求得整数部分

            remainder = remainder - quotient * divider;
            if(0 == remainder)
            {
                // 整除了,商数即结果
                result = (long)(quotient << FRACTIONAL_PLACES);
            }
            else
            {
                // 需要执行小数部分的除法
                ulong fraction = 0;     // 小数部分
                int fractionBits = 0;   // 小数点位数,初始为0
                while(0 != remainder && fractionBits < FRACTIONAL_PLACES)
                {
                    remainder <<= 1;    // 被除数右边补0
                    fractionBits++;     // 小数位数增1
                    if (remainder >= divider)
                    {
                        // 够减,小数部分左移一位并加1,且更新被除数
                        fraction = (fraction << 1) + 1;
                        remainder -= divider;
                    }
                    else
                    {
                        // 不够减,小数部分左移一位并加0
                        fraction = (fraction << 1) + 0;
                    }
                }
                result = (long)((quotient << FRACTIONAL_PLACES) + (fraction & FRACTIONAL_MASK));
            }

            // 添加符号
            result = negative ? -result : result;

            return new DFix(result);
        }

记录一下,以后补全。

定点数除法

标签:数位   cti   pre   logs   bool   左移   ide   整数   ret   

原文地址:http://www.cnblogs.com/marisa/p/6389539.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!