コード例 #1
0
ファイル: EContext.cs プロジェクト: peteroupc/Numbers
 /// <include file='../../docs.xml'
 /// path='docs/doc[@name="M:PeterO.Numbers.EContext.Copy"]/*'/>
 public EContext Copy() {
   var pcnew = new EContext(
     0,
     this.rounding,
     0,
     0,
     this.clampNormalExponents);
   pcnew.hasFlags = this.hasFlags;
   pcnew.precisionInBits = this.precisionInBits;
   pcnew.adjustExponent = this.adjustExponent;
   pcnew.simplified = this.simplified;
   pcnew.flags = this.flags;
   pcnew.exponentMax = this.exponentMax;
   pcnew.exponentMin = this.exponentMin;
   pcnew.hasExponentRange = this.hasExponentRange;
   pcnew.bigintPrecision = this.bigintPrecision;
   pcnew.rounding = this.rounding;
   pcnew.clampNormalExponents = this.clampNormalExponents;
   return pcnew;
 }
コード例 #2
0
ファイル: EContextTest.cs プロジェクト: peteroupc/Numbers
 public void TestWithUnlimitedExponents() {
   var pc = new EContext(0, ERounding.HalfUp, 0, 5, true);
   Assert.IsTrue(pc.HasExponentRange);
   pc = pc.WithUnlimitedExponents();
   Assert.IsFalse(pc.HasExponentRange);
 }
コード例 #3
0
ファイル: PrecisionContext.cs プロジェクト: peteroupc/CBOR
 internal PrecisionContext(EContext ec)
 {
     this.ec = ec;
 }
コード例 #4
0
ファイル: ETrapException.cs プロジェクト: peteroupc/Numbers
 /// <include file='../../docs.xml'
 /// path='docs/doc[@name="M:PeterO.Numbers.ETrapException.#ctor(System.Int32,PeterO.Numbers.EContext,System.Object)"]/*'/>
 public ETrapException(int flag, EContext ctx, Object result) :
   base(FlagToMessage(flag)) {
   this.error = flag;
   this.ctx = (ctx == null) ? null : ctx.Copy();
   this.result = result;
 }
コード例 #5
0
ファイル: EContextTest.cs プロジェクト: peteroupc/Numbers
 public void TestWithSimplified() {
   var pc = new EContext(0, ERounding.HalfUp, 0, 5, true);
   Assert.IsFalse(pc.IsSimplified);
   pc = pc.WithSimplified(true);
   Assert.IsTrue(pc.IsSimplified);
   pc = pc.WithSimplified(false);
   Assert.IsFalse(pc.IsSimplified);
 }
コード例 #6
0
 public T Pi(EContext ctx)
 {
     return(this.wrapper.Pi(ctx));
 }
コード例 #7
0
        private T PostProcessEx(
            T thisValue,
            EContext ctxDest,
            EContext ctxSrc,
            bool afterDivision,
            bool afterQuantize)
        {
            int thisFlags = this.GetHelper().GetFlags(thisValue);

            if (ctxDest != null && ctxSrc != null)
            {
                if (ctxDest.HasFlags)
                {
                    if (!ctxSrc.ClampNormalExponents)
                    {
                        ctxSrc.Flags &= ~EContext.FlagClamped;
                    }
                    ctxDest.Flags |= ctxSrc.Flags;
                    if ((ctxSrc.Flags & EContext.FlagSubnormal) != 0)
                    {
                        // Treat subnormal numbers as underflows
                        ctxDest.Flags |= BigNumberFlags.UnderflowFlags;
                    }
                }
            }
            if ((thisFlags & BigNumberFlags.FlagSpecial) != 0)
            {
                return((ctxDest.Flags == 0) ? this.SignalInvalid(ctxDest) : thisValue);
            }
            EInteger mant = this.GetHelper().GetMantissa(thisValue).Abs();

            if (mant.IsZero)
            {
                return(afterQuantize ? this.GetHelper().CreateNewWithFlags(
                           mant,
                           this.GetHelper().GetExponent(thisValue),
                           0) : this.wrapper.RoundToPrecision(
                           this.GetHelper().ValueOf(0),
                           ctxDest));
            }
            if (afterQuantize)
            {
                return(thisValue);
            }
            EInteger exp = this.GetHelper().GetExponent(thisValue);

            if (exp.Sign > 0)
            {
                FastInteger fastExp = FastInteger.FromBig(exp);
                if (ctxDest == null || !ctxDest.HasMaxPrecision)
                {
                    mant = this.GetHelper().MultiplyByRadixPower(mant, fastExp);
                    return(this.GetHelper().CreateNewWithFlags(
                               mant,
                               EInteger.Zero,
                               thisFlags));
                }
                if (!ctxDest.ExponentWithinRange(exp))
                {
                    return(thisValue);
                }
                FastInteger prec   = FastInteger.FromBig(ctxDest.Precision);
                FastInteger digits =
                    this.GetHelper().CreateShiftAccumulator(mant).GetDigitLength();
                prec.Subtract(digits);
                if (prec.Sign > 0 && prec.CompareTo(fastExp) >= 0)
                {
                    mant = this.GetHelper().MultiplyByRadixPower(mant, fastExp);
                    return(this.GetHelper().CreateNewWithFlags(
                               mant,
                               EInteger.Zero,
                               thisFlags));
                }
                if (afterDivision)
                {
                    int radix = this.GetHelper().GetRadix();
                    mant = NumberUtility.ReduceTrailingZeros(
                        mant,
                        fastExp,
                        radix,
                        null,
                        null,
                        null);
                    thisValue = this.GetHelper().CreateNewWithFlags(
                        mant,
                        fastExp.AsEInteger(),
                        thisFlags);
                }
            }
            else if (afterDivision && exp.Sign < 0)
            {
                FastInteger fastExp = FastInteger.FromBig(exp);
                int         radix   = this.GetHelper().GetRadix();
                mant = NumberUtility.ReduceTrailingZeros(
                    mant, fastExp, radix, null, null, new FastInteger(0));
                thisValue = this.GetHelper().CreateNewWithFlags(
                    mant,
                    fastExp.AsEInteger(),
                    thisFlags);
            }
            return(thisValue);
        }
コード例 #8
0
 private T CheckNotANumber2(T val, T val2, EContext ctx)
 {
     return(this.HandleNotANumber(val, val2, ctx));
 }
コード例 #9
0
        private T RoundBeforeOp(T val, EContext ctx)
        {
            if (ctx == null || !ctx.HasMaxPrecision)
            {
                return(val);
            }
            int thisFlags = this.GetHelper().GetFlags(val);

            if ((thisFlags & BigNumberFlags.FlagSpecial) != 0)
            {
                return(val);
            }
            FastInteger fastPrecision = FastInteger.FromBig(ctx.Precision);
            EInteger    mant          = this.GetHelper().GetMantissa(val).Abs();
            FastInteger digits        =
                this.GetHelper().CreateShiftAccumulator(mant).GetDigitLength();
            EContext ctx2 = ctx.WithBlankFlags().WithTraps(0);

            if (digits.CompareTo(fastPrecision) <= 0)
            {
                // Rounding is only to be done if the digit count is
                // too big (distinguishing this case is material
                // if the value also has an exponent that's out of range)
                return(val);
            }
            val = this.wrapper.RoundToPrecision(val, ctx2);
            // the only time rounding can signal an invalid
            // operation is if an operand is signaling NaN, but
            // this was already checked beforehand
      #if DEBUG
            if ((ctx2.Flags & EContext.FlagInvalid) != 0)
            {
                throw new
                      ArgumentException("doesn't satisfy (ctx2.Flags&FlagInvalid)==0");
            }
      #endif
            if ((ctx2.Flags & EContext.FlagInexact) != 0)
            {
                if (ctx.HasFlags)
                {
                    ctx.Flags |= BigNumberFlags.LostDigitsFlags;
                }
            }
            if ((ctx2.Flags & EContext.FlagRounded) != 0)
            {
                if (ctx.HasFlags)
                {
                    ctx.Flags |= EContext.FlagRounded;
                }
            }
            if ((ctx2.Flags & EContext.FlagSubnormal) != 0)
            {
                // Console.WriteLine("Subnormal input: " + val);
            }
            if ((ctx2.Flags & EContext.FlagUnderflow) != 0)
            {
                // Console.WriteLine("Underflow");
            }
            if ((ctx2.Flags & EContext.FlagOverflow) != 0)
            {
                bool neg = (thisFlags & BigNumberFlags.FlagNegative) != 0;
                ctx.Flags |= EContext.FlagLostDigits;
                return(this.SignalOverflow2(ctx, neg));
            }
            return(val);
        }
コード例 #10
0
 private static EContext GetContextWithFlags(EContext ctx)
 {
     return((ctx == null) ? ctx : ctx.WithBlankFlags());
 }
コード例 #11
0
        internal static EFloat FromString(
            char[] chars,
            int offset,
            int length,
            EContext ctx,
            bool throwException)
        {
            if (chars == null)
            {
                if (!throwException)
                {
                    return(null);
                }
                else
                {
                    throw new ArgumentNullException(nameof(chars));
                }
            }
            if (offset < 0)
            {
                if (!throwException)
                {
                    return(null);
                }
                else
                {
                    throw new FormatException("offset(" + offset + ") is not" +
                                              "\u0020greater" + "\u0020or equal to 0");
                }
            }
            if (offset > chars.Length)
            {
                if (!throwException)
                {
                    return(null);
                }
                else
                {
                    throw new FormatException("offset(" + offset + ") is not" +
                                              "\u0020less" + "\u0020or" + "\u0020equal to " + chars.Length);
                }
            }
            if (length < 0)
            {
                if (!throwException)
                {
                    return(null);
                }
                else
                {
                    throw new FormatException("length(" + length + ") is not" +
                                              "\u0020greater or" + "\u0020equal to 0");
                }
            }
            if (length > chars.Length)
            {
                if (!throwException)
                {
                    return(null);
                }
                else
                {
                    throw new FormatException("length(" + length + ") is not" +
                                              "\u0020less" + "\u0020or" + "\u0020equal to " + chars.Length);
                }
            }
            if (chars.Length - offset < length)
            {
                if (!throwException)
                {
                    return(null);
                }
                else
                {
                    throw new FormatException("str's length minus " + offset + "(" +
                                              (chars.Length - offset) + ") is not greater or equal to " + length);
                }
            }
            EContext b64 = EContext.Binary64;

            if (ctx != null && ctx.HasMaxPrecision && ctx.HasExponentRange &&
                !ctx.IsSimplified && ctx.EMax.CompareTo(b64.EMax) <= 0 &&
                ctx.EMin.CompareTo(b64.EMin) >= 0 &&
                ctx.Precision.CompareTo(b64.Precision) <= 0)
            {
                int tmpoffset = offset;
                int endpos    = offset + length;
                if (length == 0)
                {
                    if (!throwException)
                    {
                        return(null);
                    }
                    else
                    {
                        throw new FormatException();
                    }
                }
                if (chars[tmpoffset] == '-' || chars[tmpoffset] == '+')
                {
                    ++tmpoffset;
                }
                if (tmpoffset < endpos && ((chars[tmpoffset] >= '0' &&
                                            chars[tmpoffset] <= '9') || chars[tmpoffset] == '.'))
                {
                    EFloat ef = DoubleEFloatFromString(
                        chars,
                        offset,
                        length,
                        ctx,
                        throwException);
                    if (ef != null)
                    {
                        return(ef);
                    }
                }
            }
            return(EDecimal.FromString(
                       chars,
                       offset,
                       length,
                       EContext.Unlimited.WithSimplified(ctx != null && ctx.IsSimplified))
                   .ToEFloat(ctx));
        }
コード例 #12
0
        internal static EFloat DoubleEFloatFromString(
            char[] chars,
            int offset,
            int length,
            EContext ctx,
            bool throwException)
        {
            int tmpoffset = offset;

            if (chars == null)
            {
                if (!throwException)
                {
                    return(null);
                }
                else
                {
                    throw new ArgumentNullException(nameof(chars));
                }
            }
            if (length == 0)
            {
                if (!throwException)
                {
                    return(null);
                }
                else
                {
                    throw new FormatException();
                }
            }
            int  endStr           = tmpoffset + length;
            var  negative         = false;
            var  haveDecimalPoint = false;
            var  haveDigits       = false;
            var  haveExponent     = false;
            var  newScaleInt      = 0;
            var  digitStart       = 0;
            int  i            = tmpoffset;
            long mantissaLong = 0L;

            // Ordinary number
            if (chars[i] == '+' || chars[i] == '-')
            {
                if (chars[i] == '-')
                {
                    negative = true;
                }
                ++i;
            }
            digitStart = i;
            int digitEnd          = i;
            int decimalDigitStart = i;
            var haveNonzeroDigit  = false;
            var decimalPrec       = 0;
            int decimalDigitEnd   = i;
            var nonzeroBeyondMax  = false;
            var lastdigit         = -1;
            // 768 is maximum precision of a decimal
            // half-ULP in double format
            var maxDecimalPrec = 768;

            if (length > 21)
            {
                int eminInt = ctx.EMin.ToInt32Checked();
                int emaxInt = ctx.EMax.ToInt32Checked();
                int precInt = ctx.Precision.ToInt32Checked();
                if (eminInt >= -14 && emaxInt <= 15)
                {
                    maxDecimalPrec = (precInt <= 11) ? 21 : 63;
                }
                else if (eminInt >= -126 && emaxInt <= 127)
                {
                    maxDecimalPrec = (precInt <= 24) ? 113 : 142;
                }
            }
            for (; i < endStr; ++i)
            {
                char ch = chars[i];
                if (ch >= '0' && ch <= '9')
                {
                    var thisdigit = (int)(ch - '0');
                    haveDigits        = true;
                    haveNonzeroDigit |= thisdigit != 0;
                    if (decimalPrec > maxDecimalPrec)
                    {
                        if (thisdigit != 0)
                        {
                            nonzeroBeyondMax = true;
                        }
                        if (!haveDecimalPoint)
                        {
                            // NOTE: Absolute value will not be more than
                            // the char[] portion's length, so will fit comfortably
                            // in an 'int'.
                            newScaleInt = checked (newScaleInt + 1);
                        }
                        continue;
                    }
                    lastdigit = thisdigit;
                    if (haveNonzeroDigit)
                    {
                        ++decimalPrec;
                    }
                    if (haveDecimalPoint)
                    {
                        decimalDigitEnd = i + 1;
                    }
                    else
                    {
                        digitEnd = i + 1;
                    }
                    if (mantissaLong <= 922337203685477580L)
                    {
                        mantissaLong *= 10;
                        mantissaLong += thisdigit;
                    }
                    else
                    {
                        mantissaLong = Int64.MaxValue;
                    }
                    if (haveDecimalPoint)
                    {
                        // NOTE: Absolute value will not be more than
                        // the portion's length, so will fit comfortably
                        // in an 'int'.
                        newScaleInt = checked (newScaleInt - 1);
                    }
                }
                else if (ch == '.')
                {
                    if (haveDecimalPoint)
                    {
                        if (!throwException)
                        {
                            return(null);
                        }
                        else
                        {
                            throw new FormatException();
                        }
                    }
                    haveDecimalPoint  = true;
                    decimalDigitStart = i + 1;
                    decimalDigitEnd   = i + 1;
                }
                else if (ch == 'E' || ch == 'e')
                {
                    haveExponent = true;
                    ++i;
                    break;
                }
                else
                {
                    if (!throwException)
                    {
                        return(null);
                    }
                    else
                    {
                        throw new FormatException();
                    }
                }
            }
            if (!haveDigits)
            {
                if (!throwException)
                {
                    return(null);
                }
                else
                {
                    throw new FormatException();
                }
            }
            var  expInt        = 0;
            var  expoffset     = 1;
            var  expDigitStart = -1;
            var  expPrec       = 0;
            bool zeroMantissa  = !haveNonzeroDigit;

            haveNonzeroDigit = false;
            EFloat ef1, ef2;

            if (haveExponent)
            {
                haveDigits = false;
                if (i == endStr)
                {
                    if (!throwException)
                    {
                        return(null);
                    }
                    else
                    {
                        throw new FormatException();
                    }
                }
                char ch = chars[i];
                if (ch == '+' || ch == '-')
                {
                    if (ch == '-')
                    {
                        expoffset = -1;
                    }
                    ++i;
                }
                expDigitStart = i;
                for (; i < endStr; ++i)
                {
                    ch = chars[i];
                    if (ch >= '0' && ch <= '9')
                    {
                        haveDigits = true;
                        var thisdigit = (int)(ch - '0');
                        haveNonzeroDigit |= thisdigit != 0;
                        if (haveNonzeroDigit)
                        {
                            ++expPrec;
                        }
                        if (expInt <= 214748364)
                        {
                            expInt *= 10;
                            expInt += thisdigit;
                        }
                        else
                        {
                            expInt = Int32.MaxValue;
                        }
                    }
                    else
                    {
                        if (!throwException)
                        {
                            return(null);
                        }
                        else
                        {
                            throw new FormatException();
                        }
                    }
                }
                if (!haveDigits)
                {
                    if (!throwException)
                    {
                        return(null);
                    }
                    else
                    {
                        throw new FormatException();
                    }
                }
                expInt *= expoffset;
                if (expPrec > 12)
                {
                    // Exponent that can't be compensated by digit
                    // length without remaining beyond Int32 range
                    if (expoffset < 0)
                    {
                        return(EFloat.SignalUnderflow(ctx, negative, zeroMantissa));
                    }
                    else
                    {
                        return(EFloat.SignalOverflow(ctx, negative, zeroMantissa));
                    }
                }
            }
            if (i != endStr)
            {
                if (!throwException)
                {
                    return(null);
                }
                else
                {
                    throw new FormatException();
                }
            }
            if (expInt != Int32.MaxValue && expInt > -Int32.MaxValue &&
                mantissaLong != Int64.MaxValue && (ctx == null ||
                                                   !ctx.HasFlagsOrTraps))
            {
                if (mantissaLong == 0)
                {
                    EFloat ef = EFloat.Create(
                        EInteger.Zero,
                        EInteger.FromInt32(expInt));
                    if (negative)
                    {
                        ef = ef.Negate();
                    }
                    return(ef.RoundToPrecision(ctx));
                }
                var  finalexp = (long)expInt + (long)newScaleInt;
                long ml       = mantissaLong;
                if (finalexp >= -22 && finalexp <= 44)
                {
                    var iexp = (int)finalexp;
                    while (ml <= 900719925474099L && iexp > 22)
                    {
                        ml *= 10;
                        --iexp;
                    }
                    int iabsexp = Math.Abs(iexp);
                    if (ml < 9007199254740992L && iabsexp == 0)
                    {
                        return(EFloat.FromInt64(negative ?
                                                -mantissaLong : mantissaLong).RoundToPrecision(ctx));
                    }
                    else if (ml < 9007199254740992L && iabsexp <= 22)
                    {
                        EFloat efn =
                            EFloat.FromEInteger(NumberUtility.FindPowerOfTen(iabsexp));
                        if (negative)
                        {
                            ml = -ml;
                        }
                        EFloat efml = EFloat.FromInt64(ml);
                        if (iexp < 0)
                        {
                            return(efml.Divide(efn, ctx));
                        }
                        else
                        {
                            return(efml.Multiply(efn, ctx));
                        }
                    }
                }
                long adjexpUpperBound = finalexp + (decimalPrec - 1);
                long adjexpLowerBound = finalexp;
                if (adjexpUpperBound < -326)
                {
                    return(EFloat.SignalUnderflow(ctx, negative, zeroMantissa));
                }
                else if (adjexpLowerBound > 309)
                {
                    return(EFloat.SignalOverflow(ctx, negative, zeroMantissa));
                }
                if (negative)
                {
                    mantissaLong = -mantissaLong;
                }
                long absfinalexp = Math.Abs(finalexp);
                ef1 = EFloat.Create(mantissaLong, (int)0);
                ef2 = EFloat.FromEInteger(NumberUtility.FindPowerOfTen(absfinalexp));
                if (finalexp < 0)
                {
                    EFloat efret = ef1.Divide(ef2, ctx);

                    /* Console.WriteLine("div " + ef1 + "/" + ef2 + " -> " + (efret));
                     */return(efret);
                }
                else
                {
                    return(ef1.Multiply(ef2, ctx));
                }
            }
            EInteger mant = null;
            EInteger exp  = (!haveExponent) ? EInteger.Zero :
                            EInteger.FromSubstring(chars, expDigitStart, endStr);

            if (expoffset < 0)
            {
                exp = exp.Negate();
            }
            exp = exp.Add(newScaleInt);
            if (nonzeroBeyondMax)
            {
                exp = exp.Subtract(1);
                ++decimalPrec;
            }
            EInteger adjExpUpperBound = exp.Add(decimalPrec).Subtract(1);
            EInteger adjExpLowerBound = exp;

            // DebugUtility.Log("exp=" + adjExpLowerBound + "~" + (adjExpUpperBound));
            if (adjExpUpperBound.CompareTo(-326) < 0)
            {
                return(EFloat.SignalUnderflow(ctx, negative, zeroMantissa));
            }
            else if (adjExpLowerBound.CompareTo(309) > 0)
            {
                return(EFloat.SignalOverflow(ctx, negative, zeroMantissa));
            }
            if (zeroMantissa)
            {
                EFloat ef = EFloat.Create(
                    EInteger.Zero,
                    exp);
                if (negative)
                {
                    ef = ef.Negate();
                }
                return(ef.RoundToPrecision(ctx));
            }
            else if (decimalDigitStart != decimalDigitEnd)
            {
                if (digitEnd - digitStart == 1 && chars[digitStart] == '0')
                {
                    mant = EInteger.FromSubstring(
                        chars,
                        decimalDigitStart,
                        decimalDigitEnd);
                }
                else
                {
                    char[] ctmpstr = Extras.CharsConcat(
                        chars,
                        digitStart,
                        digitEnd - digitStart,
                        chars,
                        decimalDigitStart,
                        decimalDigitEnd - decimalDigitStart);
                    mant = EInteger.FromString(ctmpstr);
                }
            }
            else
            {
                mant = EInteger.FromSubstring(chars, digitStart, digitEnd);
            }
            if (nonzeroBeyondMax)
            {
                mant = mant.Multiply(10).Add(1);
            }
            if (negative)
            {
                mant = mant.Negate();
            }
            return(EDecimal.Create(mant, exp).ToEFloat(ctx));
        }
コード例 #13
0
ファイル: TrappableRadixMath.cs プロジェクト: gritor/adfsmfa
        private T TriggerTraps(
            T result,
            EContext src,
            EContext dst)
        {
            if (src == null || src.Flags == 0)
            {
                return(result);
            }
            if (dst != null && dst.HasFlags)
            {
                dst.Flags |= src.Flags;
            }
            int traps = (dst != null) ? dst.Traps : 0;

            traps &= src.Flags;
            if (traps == 0)
            {
                return(result);
            }
            int mutexConditions = traps & (~(
                                               EContext.FlagClamped | EContext.FlagInexact | EContext.FlagRounded | EContext.FlagSubnormal));

            if (mutexConditions != 0)
            {
                for (var i = 0; i < 32; ++i)
                {
                    int flag = mutexConditions & (i << 1);
                    if (flag != 0)
                    {
                        ThrowTrapException(flag, dst, result);
                    }
                }
            }
            if ((traps & EContext.FlagSubnormal) != 0)
            {
                ThrowTrapException(
                    traps & EContext.FlagSubnormal,
                    dst,
                    result);
            }
            if ((traps & EContext.FlagInexact) != 0)
            {
                ThrowTrapException(
                    traps & EContext.FlagInexact,
                    dst,
                    result);
            }
            if ((traps & EContext.FlagRounded) != 0)
            {
                ThrowTrapException(
                    traps & EContext.FlagRounded,
                    dst,
                    result);
            }
            if ((traps & EContext.FlagClamped) != 0)
            {
                ThrowTrapException(
                    traps & EContext.FlagClamped,
                    dst,
                    result);
            }
            return(result);
        }
コード例 #14
0
ファイル: TrappableRadixMath.cs プロジェクト: gritor/adfsmfa
 private static EContext GetTrappableContext(EContext ctx)
 {
     return((ctx == null) ? null : ((ctx.Traps == 0) ? ctx :
                                    ctx.WithBlankFlags()));
 }