/******************************************************************************/ /* */ /* RVM.Number.cls - The value model (the RVM's runtime) */ /* ==================================================== */ /* */ /* An immutable decimal number that travels between operations WITHOUT being */ /* serialised to a string. It carries (sign, digits, exp) plus the NUMERIC */ /* settings in force when it was created (createdDigits, form) and a lazy */ /* string cache -- so a value keeps the precision it was born with and only */ /* becomes text when text is actually needed (Say, concat, comparison...). */ /* */ /* The DECIMAL MECHANICS are ooRexx's (NumberStringMath.cpp, */ /* NumberStringMath2.cpp): the DIGITS+1 window, the magnitude fast paths, */ /* checkNumber truncation, the windowed subtract cascade, the exact power */ /* working precision, as private routines and methods. Rounding and layout */ /* are apart: adjustPrecision rounds the NUMBER (no text), and string lays */ /* out the TEXT (no rounding). See doc/02-values-and-arithmetic.md. */ /* */ /* The number model */ /* ---------------- */ /* sign -- -1 / 0 / 1 (0 iff the number is exactly zero) */ /* digits -- significant digits as a string, no leading zeros, KEEPING */ /* trailing zeros (they carry scale). "0" for zero. */ /* exp -- power of ten of the LAST digit */ /* so the value is sign * digits * 10**exp. */ /* 1.5 -> (1, "15", -1) 2.50 -> (1, "250", -2) */ /* 100 -> (1, "1", 2) 0 -> (0, "0", 0) */ /* */ /* This file is part of the RVM, the Rexx Virtual Machine */ /* [See https://rexx.epbcn.com/rexx-parser/] */ /* */ /* This file is derived from the ooRexx interpreter: the decimal arithmetic */ /* (NumberStringMath.cpp, NumberStringMath2.cpp, NumberStringClass.cpp, */ /* IntegerClass.cpp). It is therefore distributed under the Common Public */ /* License v1.0, not under the Apache License 2.0 that covers the rest of the */ /* RVM (see NOTICE). */ /* */ /* Copyright (c) 1995, 2004 IBM Corporation. All rights reserved. */ /* Copyright (c) 2005-2026 Rexx Language Association. All rights reserved. */ /* Copyright (c) 2026 Josep Maria Blasco */ /* */ /* This program and the accompanying materials are made available under the */ /* terms of the Common Public License v1.0 which accompanies this */ /* distribution. A copy is also available at the following address: */ /* https://www.oorexx.org/license.html */ /* */ /******************************************************************************/ -- Host precision for the bookkeeping arithmetic of this package (exponents, -- lengths, whole-number values). Exponents reach 999999999 and intermediate -- sums like exp + length go past it; at the default DIGITS 9 they would round. ::Options Digits 20 ::Class RVM.Number Public /******************************************************************************/ /* State (all private; immutable after init). */ /******************************************************************************/ ::Attribute sign Get -- -1 / 0 / 1 ::Attribute sign Set Private ::Attribute digits Get -- mantissa string, no leading zeros ::Attribute digits Set Private ::Attribute exp Get -- exponent of the last digit ::Attribute exp Set Private ::Attribute createdDigits Get -- NUMERIC DIGITS in force at creation ::Attribute createdDigits Set Private ::Attribute form Get -- NUMERIC FORM in force at creation ::Attribute form Set Private ::Attribute stringCache Get Private ::Attribute stringCache Set Private /******************************************************************************/ /* Constructors (class methods) */ /******************************************************************************/ /* fromString(s, ctx) : parse a Rexx numeric string into a Number, recording */ /* the current NUMERIC settings. The ORIGINAL TEXT is kept as the string cache */ /* so that str(num(s)) == s exactly (007 stays 007, 1.50 stays 1.50). Returns */ /* .Nil if s is not a valid Rexx number (the caller decides the error). */ ::Method fromString Class Use Strict Arg s, ctx = .Nil If ctx == .Nil Then Do d = 9 ; f = "SCIENTIFIC" End Else Do d = ctx~digits ; f = ctx~form End parsed = .RVM.Number~parseNumber(s) -- "sign digits exp" or "" If parsed == "" Then Return .Nil Parse Var parsed sgn dig ex n = .RVM.Number~new n~setState( sgn, dig, ex, d, f ) -- Keep the literal's own text as the string value, but canonicalise it the -- way ooRexx does when it builds a numeric literal's stringrep: lower-case e -- becomes E (say 6e0 -> 6E0), and a leading + is dropped. Everything else -- -- leading zeros (007), trailing zeros (1.50), a written exponent sign -- (1.5E+3) -- is preserved. This keeps str(num(s)) observationally faithful. n~setCache( .RVM.Number~canonLiteral(s) ) Return n /* Canonicalise a numeric literal's own text to its ooRexx string value: */ /* uppercase the exponent marker, drop a leading '+', keep the rest verbatim. */ ::Method canonLiteral Class Use Strict Arg s s = Strip(s) If Left(s, 1) == "+" Then s = Substr(s, 2) Return s~changeStr("e", "E") /* fromParts(sign, digits, exp, ctx) : build a Number from a freshly computed */ /* result and round it to the context DIGITS (adjustPrecision). No text cache. */ ::Method fromParts Class Use Strict Arg sgn, dig, ex, ctx n = .RVM.Number~new n~setState( sgn, dig, ex, ctx~digits, ctx~form ) n~adjustPrecision( ctx~digits ) Return n /* Internal raw setter (used by the constructors and by operators). */ ::Method setState Expose sign digits exp createdDigits form stringCache Use Strict Arg sign, digits, exp, createdDigits, form stringCache = .Nil -- Normalise canonical zero. If digits == "0" | digits == "" Then Do sign = 0 ; digits = "0" ; exp = 0 End ::Method setCache Expose stringCache Use Strict Arg stringCache /******************************************************************************/ /* Queries */ /******************************************************************************/ ::Method isZero Expose sign Return sign == 0 ::Method digitsCount Expose digits Return Length(digits) /* LOSTDIGITS: an operator was given an operand with more significant digits */ /* than NUMERIC DIGITS. The NUMERIC context decides what that means (the */ /* interpreter's context raises the condition; an internal working context */ /* ignores it). */ ::Method checkLost Expose digits Use Strict Arg ctx If Length(digits) > ctx~digits Then ctx~lostDigits( self ) /* Round-half-up this number IN PLACE to at most 'numDigits' significant */ /* digits, strip leading zeros, renormalise zero, and RECORD numDigits as the */ /* createdDigits. This is the NUMBER half of the formatting (no text). */ /* Mirrors NumberString::adjustPrecision / mathRound. */ ::Method adjustPrecision Expose sign digits exp createdDigits stringCache Use Strict Arg numDigits stringCache = .Nil If digits \== "0" & Length(digits) > numDigits Then Do dropped = Length(digits) - numDigits roundUp = ( Substr(digits, numDigits + 1, 1) >= 5 ) kept = Left(digits, numDigits) exp = exp + dropped If roundUp Then Do kept = .RVM.Number~addDigits(kept, "1") If Length(kept) > numDigits Then Do exp = exp + (Length(kept) - numDigits) kept = Left(kept, numDigits) End End digits = kept End digits = .RVM.Number~stripLeadingZeros(digits) If digits == "0" Then Do sign = 0 ; exp = 0 End Else If Length( exp ) > 8 Then Do -- The exponent must fit in nine digits (checkOverflow). A shorter one -- always does. Numeric Digits 40 If exp + Length(digits) - 1 > 999999999 Then Raise Syntax 42.901 Array( exp + Length(digits) - 1, 9 ) If exp < -999999999 Then Raise Syntax 42.902 Array( exp, 9 ) End createdDigits = numDigits /******************************************************************************/ /* Arithmetic operators. 'other' is always a Number; 'ctx' gives DIGITS/ */ /* FUZZ/FORM. Each returns a NEW Number. The magnitude mechanics are ooRexx's */ /* (addSub window, checkNumber truncation, etc.), as private routines of this */ /* file. */ /******************************************************************************/ /* plus / minus : addSub with the DIGITS+1 window. minus flips other's sign, */ /* exactly as RexxAdd was called with Negate(operand). */ ::Method plus Expose sign digits exp Use Strict Arg other, ctx -- The exact case (see ExactAddSub) first. If sign \== 0 Then Do bSign = other~sign If bSign \== 0 Then Do bDig = other~digits; bExp = other~exp; d = ctx~digits minExp = Min( exp, bExp ) If Length( digits ) + exp - minExp <= d, Length( bDig ) + bExp - minExp <= d Then Return ExactAddSub( sign, digits, exp, bSign, bDig, bExp, minExp, ctx ) End End self~checkLost( ctx ) ; other~checkLost( ctx ) Return self~addSub( other~sign, other~digits, other~exp, ctx ) ::Method minus Expose sign digits exp Use Strict Arg other, ctx If sign \== 0 Then Do bSign = other~sign If bSign \== 0 Then Do bDig = other~digits; bExp = other~exp; d = ctx~digits minExp = Min( exp, bExp ) If Length( digits ) + exp - minExp <= d, Length( bDig ) + bExp - minExp <= d Then Return ExactAddSub( sign, digits, exp, -bSign, bDig, bExp, minExp, ctx ) End End self~checkLost( ctx ) ; other~checkLost( ctx ) -- Subtraction is addition of the negated right operand. Return self~addSub( -other~sign, other~digits, other~exp, ctx ) /* The shared add/subtract core: faithful to NumberString::addSub. Operates on */ /* self's (sign,digits,exp) and the right operand's, returns a new Number. */ ::Method addSub Expose sign digits exp Use Strict Arg bSign, bDig, bExp, ctx d = ctx~digits maxLength = d + 1 aSign = sign ; aDig = digits ; aExp = exp -- Zero operands: return a clone of the other, rounded to DIGITS (setupNumber: -- round only if wider than DIGITS). This is what keeps 1E20+1 = 1E+20. If aDig == "0" Then Return .RVM.Number~fromPartsSigned( bSign, bDig, bExp, ctx ) If bDig == "0" Then Return .RVM.Number~fromPartsSigned( aSign, aDig, aExp, ctx ) -- checkNumber: truncate (NOT round) each operand to DIGITS+1 digits. Parse Value .RVM.Number~truncToMax(aDig, aExp, maxLength) With aDig aExp Parse Value .RVM.Number~truncToMax(bDig, bExp, maxLength) With bDig bExp aLen = Length(aDig) ; bLen = Length(bDig) minExp = Min(aExp, bExp) adjA = aExp - minExp ; adjB = bExp - minExp -- Magnitude-gap fast exits: an operand that cannot reach the other's window -- is returned unchanged (its own length kept). If (adjA + aLen) > (bLen + d) Then Return .RVM.Number~fromPartsSigned( aSign, aDig, aExp, ctx ) If (adjB + bLen) > (aLen + d) Then Return .RVM.Number~fromPartsSigned( bSign, bDig, bExp, ctx ) -- Window discard: drop low-order digits outside the maxLength window. adjADigits = (aLen + adjA) - maxLength adjBDigits = (bLen + adjB) - maxLength If adjADigits > 0 | adjBDigits > 0 Then Do adjustDigits = Max(adjADigits, adjBDigits) If adjA \== 0 Then Do If adjustDigits < adjA Then Do bDig = Left(bDig, bLen - adjustDigits) ; bExp += adjustDigits bLen = Length(bDig) ; adjustDigits = 0 End Else Do bDig = Left(bDig, bLen - adjA) ; bExp += adjA bLen = Length(bDig) ; adjustDigits -= adjA ; adjA = 0 End End Else If adjB \== 0 Then Do If adjustDigits < adjB Then Do aDig = Left(aDig, aLen - adjustDigits) ; aExp += adjustDigits aLen = Length(aDig) ; adjustDigits = 0 End Else Do aDig = Left(aDig, aLen - adjB) ; aExp += adjB aLen = Length(aDig) ; adjustDigits -= adjB ; adjB = 0 End End If adjustDigits > 0 Then Do aDig = Left(aDig, Length(aDig) - adjustDigits) ; aExp += adjustDigits bDig = Left(bDig, Length(bDig) - adjustDigits) ; bExp += adjustDigits End If aDig == "" Then aDig = "0" If bDig == "" Then bDig = "0" aLen = Length(aDig) ; bLen = Length(bDig) minExp = Min(aExp, bExp) ; adjA = aExp - minExp ; adjB = bExp - minExp End If aSign == bSign Then Do -- Same sign -> addition of magnitudes, keeping scale. expMin = Min(aExp, bExp) A = aDig || Copies("0", aExp - expMin) B = bDig || Copies("0", bExp - expMin) Return .RVM.Number~fromPartsSigned( aSign, .RVM.Number~addDigits(A, B), expMin, ctx ) End -- Different signs -> subtraction of magnitudes via the windowed cascade. aRank = adjA + aLen ; bRank = adjB + bLen Select When aRank > bRank Then aLarger = 1 When bRank > aRank Then aLarger = 0 Otherwise Do cmp = .RVM.Number~compareAligned(aDig, bDig) If cmp == 0 Then Return .RVM.Number~fromPartsSigned( 0, "0", 0, ctx ) aLarger = (cmp > 0) End End rExp = (adjA \== 0)~?(bExp, aExp) If aLarger Then Return .RVM.Number~fromPartsSigned( aSign, .RVM.Number~subWindowed(aDig, adjA, bDig, adjB), rExp, ctx ) Return .RVM.Number~fromPartsSigned( bSign, .RVM.Number~subWindowed(bDig, adjB, aDig, adjA), rExp, ctx ) /* times : multiplication (keeps scale; result exp is the sum of exponents). */ ::Method times Expose sign digits exp Use Strict Arg other, ctx d = ctx~digits ; maxLength = d + 1 aSign = sign ; aDig = digits ; aExp = exp bSign = other~sign ; bDig = other~digits ; bExp = other~exp self~checkLost( ctx ) ; other~checkLost( ctx ) -- before the zero shortcut If aDig == "0" | bDig == "0" Then Return .RVM.Number~fromPartsSigned( 0, "0", 0, ctx ) Parse Value .RVM.Number~truncToMax(aDig, aExp, maxLength) With aDig aExp Parse Value .RVM.Number~truncToMax(bDig, bExp, maxLength) With bDig bExp rSign = (aSign == bSign)~?( 1, -1 ) rDig = .RVM.Number~mulDigits(aDig, bDig) rExp = aExp + bExp Return .RVM.Number~fromPartsSigned( rSign, rDig, rExp, ctx ) /* divide : long division to DIGITS+1 then round; trailing zeros dropped. */ ::Method divide Expose sign digits exp Use Strict Arg other, ctx d = ctx~digits ; maxDigits = d + 1 aSign = sign ; aDig = digits ; aExp = exp bSign = other~sign ; bDig = other~digits ; bExp = other~exp If bDig == "0" Then Raise Syntax 42.3 If aDig == "0" Then Return .RVM.Number~fromPartsSigned( 0, "0", 0, ctx ) self~checkLost( ctx ) ; other~checkLost( ctx ) -- after the zero checks rSign = (aSign == bSign)~?( 1, -1 ) Parse Value .RVM.Number~truncToMax(aDig, aExp, maxDigits) With aDig aExp Parse Value .RVM.Number~truncToMax(bDig, bExp, maxDigits) With bDig bExp Parse Value .RVM.Number~longDivide(aDig, aExp, bDig, bExp, maxDigits) With quo scale Return .RVM.Number~fromPartsStripped( rSign, .RVM.Number~stripLeadingZeros(quo), scale, ctx ) /* intDivide (%) and remainder (//): share the integer long division core. */ ::Method intDivide Expose sign digits exp Use Strict Arg other, ctx Parse Value self~intQuotient(other, ctx) With quo remDig remExp qSign If quo == "0" Then Return .RVM.Number~fromPartsSigned( 0, "0", 0, ctx ) Return .RVM.Number~fromPartsSigned( qSign, quo, 0, ctx ) ::Method remainder Expose sign digits exp Use Strict Arg other, ctx Parse Value self~intQuotient(other, ctx, "//") With quo remDig remExp qSign aSign = sign If remDig == "0" Then Return .RVM.Number~fromPartsSigned( 0, "0", 0, ctx ) -- |a| < |b| : quotient zero, remainder is the dividend itself, own scale. If quo == "0" Then Do d = ctx~digits Parse Value .RVM.Number~truncToMax(digits, exp, d + 1) With aDig aExp Return .RVM.Number~fromPartsSigned( aSign, aDig, aExp, ctx ) End Return .RVM.Number~fromPartsSigned( aSign, .RVM.Number~stripLeadingZeros(remDig), remExp, ctx ) /* The shared %/// core. Returns "quotient remDigits remExp quotientSign". */ /* 'op' is the operator: a quotient too wide is 26.11 for %, 26.12 for //. */ ::Method intQuotient Expose sign digits exp Use Strict Arg other, ctx, op = "%" d = ctx~digits aSign = sign ; aDig = digits ; aExp = exp bSign = other~sign ; bDig = other~digits ; bExp = other~exp If bDig == "0" Then Raise Syntax 42.3 If aDig == "0" Then Return "0 0 0 0" self~checkLost( ctx ) ; other~checkLost( ctx ) -- after the zero checks rSign = (aSign == bSign)~?( 1, -1 ) maxLength = d + 1 Parse Value .RVM.Number~truncToMax(aDig, aExp, maxLength) With aDig aExp Parse Value .RVM.Number~truncToMax(bDig, bExp, maxLength) With bDig bExp -- From the exponents alone: |a| < |b| (the quotient is zero, the remainder -- a), or a quotient of more than DIGITS digits. Numeric Digits 40 adjA = aExp + Length(aDig) - 1 adjB = bExp + Length(bDig) - 1 If adjA < adjB Then Return "0" aDig aExp 0 If adjA - adjB > d Then Do If op == "//" Then Raise Syntax 26.12 Additional( "//" ) Raise Syntax 26.11 Additional( "%" ) End Numeric Digits expMin = Min(aExp, bExp) numer = aDig || Copies("0", aExp - expMin) denom = bDig || Copies("0", bExp - expMin) quotient = "" ; remainder = "" Loop k = 1 To Length(numer) work = .RVM.Number~stripLeadingZeros( remainder || Substr(numer, k, 1) ) q = 0 Loop dd = 9 To 1 By -1 If .RVM.Number~compareDigits( .RVM.Number~mulDigits(denom, dd), work ) <= 0 Then Do q = dd ; Leave End End quotient = quotient || q remainder = .RVM.Number~subDigits( work, .RVM.Number~mulDigits(denom, q) ) End quotient = .RVM.Number~stripLeadingZeros(quotient) If quotient \== "0" & Length(quotient) > d Then Do If op == "//" Then Raise Syntax 26.12 Additional( "//" ) Raise Syntax 26.11 Additional( "%" ) End If quotient == "0" Then qSign = 0 Else qSign = rSign Return quotient .RVM.Number~stripLeadingZeros(remainder) expMin qSign /* power : base ** whole exponent, binary exponentiation at raised precision. */ ::Method power Expose sign digits exp Use Strict Arg other, ctx d = ctx~digits -- The exponent (a Number or a plain string) must be a whole number at the -- current DIGITS; anything else, a non-number included, is error 26.8. n = wholeNumber( other, d ) If n == .Nil Then Raise Syntax 26.8 Additional( str( other ) ) negativePower = ( n < 0 ) n = Abs( n ) self~checkLost( ctx ) -- the base (not the power) -- Prepare the base like every other operator: truncate to DIGITS+1 and round -- to DIGITS+1 (as ooRexx's power does). Parse Value .RVM.Number~truncToMax(digits, exp, d + 1) With bDig bExp -- A zero base: 0**0 is 1, 0**n is 0, and 0**-n is an overflow (42.903). If sign == 0 Then Do If negativePower Then Raise Syntax 42.903 If n == 0 Then Return .RVM.Number~fromString("1", ctx) Return .RVM.Number~fromString("0", ctx) End -- The result's exponent is known in advance: when it would pass the largest -- exponent, the power overflows before any work is done (42.1). If Abs( bExp + Length( bDig ) - 1 ) * n > 999999999 Then Raise Syntax 42.1 Additional( str( self ), "**", str( other ) ) If n == 0 Then Return .RVM.Number~fromString("1", ctx) -- x**0 = 1 base = .RVM.Number~fromPartsSignedWith( sign, bDig, bExp, d + 1, ctx~form ) -- Working precision, matching ooRexx exactly: digits + Length(n) + 1. work = d + Length(n) + 1 workCtx = .RVM.Number~ctxWith( work, 0, ctx~form ) result = .RVM.Number~fromString("1", workCtx) b = base~withContextDigits( work ) Loop While n > 0 If n // 2 == 1 Then result = result~times( b, workCtx ) n = n % 2 If n > 0 Then b = b~times( b, workCtx ) End If negativePower Then Do -- Reciprocal for a negative exponent. ooRexx's dividePower produces the -- quotient to work+1 significant digits and rounds ONCE, at the very end, -- to the caller's DIGITS. Dividing at 'work' and then rounding to DIGITS -- would double-round (35**-3 at d12: 1/42875 to 14 digits is ...035, which -- rounds up to ...604, but the exact ...0350349 rounds DOWN to ...603). -- So take the reciprocal at work+1 digits and let the single final round fix -- it. recipCtx = .RVM.Number~ctxWith( work + 1, 0, ctx~form ) result = .RVM.Number~fromString("1", recipCtx)~divide( result, recipCtx ) End -- Round to the caller's DIGITS (like RexxAdd(result,"0",digits)), then drop -- trailing zeros to lowest terms. Unlike division, power does NOT re-expand -- the integer scale: (2e1)**5 keeps structure (32,5), so a later -- (2e1)**5 * 5.646e7 is 1.80672E+14 -- the exponent stays with the value, as -- ooRexx's StripResultZeros leaves it (its plain string still reads 3200000). rounded = result~withContextDigits( d ) rounded~adjustPrecision( d ) rounded~stripAllZeros Return rounded /* negate : prefix '-'. Copy, round to DIGITS, flip the sign. Never serialise. */ ::Method negate Expose sign digits exp Use Strict Arg ctx self~checkLost( ctx ) n = .RVM.Number~fromPartsSigned( -sign, digits, exp, ctx ) Return n /* identity : prefix '+'. Faithful to NumberString::plus with no argument: */ /* returns self ONLY when there is no cached string, createdDigits == ctx */ /* digits and form matches; otherwise a copy rounded to DIGITS (dropping the */ /* original literal text). So +962.2949 at DIGITS 5 is 962.29 and +007 is 7 -- */ /* the prefix normalises, discarding the verbatim literal. */ ::Method identity Expose sign digits exp createdDigits form stringCache Use Strict Arg ctx If stringCache == .Nil & createdDigits == ctx~digits & form == ctx~form Then Return self self~checkLost( ctx ) Return .RVM.Number~fromPartsSigned( sign, digits, exp, ctx ) /* compare : NORMAL numeric comparison -> -1 / 0 / 1, under DIGITS-FUZZ. */ /* Rexx compares by the sign of (a - b) computed at DIGITS-FUZZ digits. */ ::Method compare Expose sign digits exp Use Strict Arg other, ctx effective = Max( ctx~digits - ctx~fuzz, 1 ) -- The exact case: both operands, aligned at the smaller exponent, -- have at most DIGITS-FUZZ digits. Then neither is LOSTDIGITS (at DIGITS -- nor at DIGITS-FUZZ), the subtraction below is exact, and its sign is -- that of the exact difference. bDig = other~digits; bExp = other~exp minExp = Min( exp, bExp ) If Length( digits ) + exp - minExp <= effective, - Length( bDig ) + bExp - minExp <= effective Then Do Numeric Digits effective + 2 a = digits || Copies( "0", exp - minExp ) b = bDig || Copies( "0", bExp - minExp ) If sign < 0 Then a = "-" || a If other~sign < 0 Then b = "-" || b Return Sign( a - b ) End -- LOSTDIGITS is checked at DIGITS here, and then again by the subtraction at -- DIGITS-FUZZ (so under FUZZ a shorter operand can raise it too). self~checkLost( ctx ) ; other~checkLost( ctx ) effCtx = .RVM.Number~ctxWith( effective, 0, ctx~form, ctx ) diff = self~minus( other, effCtx ) If diff~isZero Then Return 0 If diff~sign < 0 Then Return -1 Return 1 /******************************************************************************/ /* numberValue / unsignedNumberValue : the whole number a value stands for */ /* when it is used where a whole number is required (the ** exponent, and the */ /* whole-number arguments of the built-in functions). */ /* */ /* numberValue(d) -> the whole number (a Rexx string), or .Nil if */ /* the value is not one at 'd' digits of precision */ /* unsignedNumberValue(d) -> the same, but a negative value is .Nil */ /* */ /* 'd' is the precision of the conversion: the current NUMERIC DIGITS for the */ /* ** exponent, WholeDigits (18 or 9) for other whole-number operands. The */ /* value is first rounded to 'd' significant digits; it must then have no */ /* fractional part, and its magnitude must be at most */ /* 10**min(d, WholeDigits) - 1. So at DIGITS 9, */ /* 1.0000000005 is 1 and 1.9999999999 is 2, but 2.5 and 1000000000 are not */ /* whole numbers. */ /* */ /* Quirk kept on purpose: a value that is entirely fractional and rounds up */ /* to one (0.9999 at DIGITS 3) gives 1 WHATEVER ITS SIGN, so the string */ /* -0.9999 is 1, not -1: with x = '-0.9999', 2 ** x at DIGITS 3 is 2, not */ /* 0.5. (2 ** -0.9999 is 0.5: there the prefix minus rounds its operand to */ /* 1.00 first.) */ /******************************************************************************/ -- The widest whole number a conversion can produce, in digits. It depends on -- the build: 18 on 64-bit, 9 on 32-bit (the host's own internal digits). ::Attribute WholeDigits Class Get ::Method activate Class Expose WholeDigits WholeDigits = .RexxInfo~internalDigits ::Method numberValue Use Strict Arg numDigits Return self~convertWhole( numDigits, 0 ) ::Method unsignedNumberValue Use Strict Arg numDigits Return self~convertWhole( numDigits, 1 ) ::Method convertWhole Private Expose sign digits exp Use Strict Arg numDigits, unsigned If sign == 0 Then Return 0 -- exactly zero If unsigned, sign < 0 Then Return .Nil -- no negative lengths length = Length( digits ) numberExp = exp -- The common case: an integer with no more than 'numDigits' digits. If length <= numDigits, numberExp >= 0 Then Do v = .RVM.Number~composeWhole( digits, length, 0, numberExp, numDigits ) If v == .Nil Then Return .Nil If sign < 0 Then Return "-"v Return v End -- Round to 'numDigits': keep the first numDigits digits, move the exponent -- up by what was dropped, and remember whether the first dropped digit -- rounds the kept part up (carry). carry = 0 If length > numDigits Then Do numberExp = numberExp + ( length - numDigits ) length = numDigits If Substr( digits, numDigits + 1, 1 ) >= 5 Then carry = 1 End -- Every kept digit right of the decimal point must be zero -- or, when the -- rounding carries into them, nine (the carry turns them all into zeros). If numberExp < 0 Then Do decimalPos = -numberExp fill = "0" If carry Then Do -- The point lies left of every kept digit: a padding zero would stay. If decimalPos > length Then Return .Nil fill = "9" End If decimalPos >= length Then Do decimalPos = length start = 1 End Else start = length + numberExp + 1 If Substr( digits, start, decimalPos ) \== Copies( fill, decimalPos ) Then Return .Nil End -- All fractional: the value is 0, or 1 through the carry. The sign is NOT -- applied here (see the quirk above). The unsigned conversion compares with -- the ORIGINAL digit count, the signed one with the rounded length. If unsigned Then allFraction = ( -numberExp >= Length( digits ) ) Else allFraction = ( -numberExp >= length ) If allFraction Then Return carry If numberExp < 0 Then v = .RVM.Number~composeWhole( digits, length + numberExp, carry, 0, numDigits ) Else v = .RVM.Number~composeWhole( digits, length, carry, numberExp, numDigits ) If v == .Nil Then Return .Nil If sign < 0 Then Return "-"v Return v /* composeWhole : the whole number made of the first 'intLength' digits, plus */ /* 'carry', times 10**exponent -- or .Nil when it is wider than WholeDigits or */ /* larger than 10**min(numDigits, WholeDigits) - 1. */ ::Method composeWhole Class Use Strict Arg digits, intLength, carry, exponent, numDigits maxDigits = .RVM.Number~WholeDigits If exponent + intLength > maxDigits Then Return .Nil Numeric Digits 40 If intLength > 0 Then v = Left( digits, intLength ) + carry Else v = carry v = v * 10 ** exponent If v > 10 ** Min( numDigits, maxDigits ) - 1 Then Return .Nil Return v /******************************************************************************/ /* string : lazy, cached serialisation. This is the LAYOUT half of the */ /* formatting -- plain vs scientific vs engineering -- with NO rounding */ /* (adjustPrecision already rounded). Uses createdDigits for the exp trigger. */ /******************************************************************************/ ::Method string Expose sign digits exp createdDigits form stringCache If stringCache \== .Nil Then Return stringCache If sign == 0 Then Do stringCache = "0" ; Return "0" End s = self~layout( digits, exp, createdDigits, form ) If sign < 0 Then s = "-" || s stringCache = s Return s /* The pure layout routine: sign already handled by the caller. */ ::Method layout Private Use Strict Arg dig, ex, cd, frm numLen = Length(dig) adjustedExp = ex + numLen - 1 -- Scientific when the adjusted exponent reaches createdDigits, or the last -- digit's exponent falls below -2*createdDigits. If adjustedExp >= cd | ex < -2 * cd Then Return self~expForm( dig, adjustedExp, frm ) If ex >= 0 Then Return dig || Copies("0", ex) pointPos = numLen + ex If pointPos > 0 Then Return Left(dig, pointPos) || "." || Substr(dig, pointPos + 1) Return "0." || Copies("0", -pointPos) || dig /* Exponential / engineering form. SCIENTIFIC: one digit before the point. */ /* ENGINEERING: the integer part has 1..3 digits and the exponent is a */ /* multiple of 3. */ ::Method expForm Private Use Strict Arg dig, adjustedExp, frm If frm == "ENGINEERING" Then Do -- Shift so the exponent is a multiple of 3 and 1..3 integer digits remain. e = adjustedExp -- number of integer digits wanted: ((e mod 3)+3 mod 3) + 1 r = e // 3 If r < 0 Then r = r + 3 intCount = r + 1 e = e - r If Length(dig) < intCount Then dig = dig || Copies("0", intCount - Length(dig)) intPart = Left(dig, intCount) fracPart = Substr(dig, intCount + 1) If fracPart == "" Then mant = intPart Else mant = intPart || "." || fracPart Return mant || ExpSuffix( e ) End -- SCIENTIFIC If Length(dig) == 1 Then mant = dig Else mant = Left(dig, 1) || "." || Substr(dig, 2) Return mant || ExpSuffix( adjustedExp ) /******************************************************************************/ /* Small internal helpers on the instance. */ /******************************************************************************/ /* Drop trailing zeros so a division/power result carries its own precision, */ /* then RE-EXPAND the structure to whatever its plain string would re-parse to. */ /* */ /* ooRexx strips a quotient/power to lowest terms, but the value's OBSERVABLE */ /* structure is that of its canonical string. When the number lands in plain */ /* (non-scientific) range, that string is the integer/decimal form, which */ /* re-parses with the integer zeros intact: 4630/1 -> strip (463,1) -> but its */ /* plain string "4630" re-parses to (4630,0), so a later (4630/1)*345.435 keeps */ /* the scale and gives 1599364.050. When it lands in scientific range, the plain */ /* form does not apply and the stripped mantissa stands (48**2 at DIGITS 3 is */ /* 2.3E+3, not 2.30E+3). So: strip fully, then if the result is plain, push the */ /* exponent back down to 0 by re-appending the integer zeros. */ ::Method stripTrailingZeros Expose sign digits exp createdDigits form stringCache stringCache = .Nil -- Strip fully to lowest terms. Do While Length(digits) > 1 & Right(digits, 1) == "0" digits = Left(digits, Length(digits) - 1) exp = exp + 1 End If sign == 0 Then Return -- Would this lay out plain or scientific? (Same test as 'layout'.) adjustedExp = exp + Length(digits) - 1 isScientific = ( adjustedExp >= createdDigits | exp < -2 * createdDigits ) -- Plain and integer-valued (exp > 0): re-append the scale zeros so the -- structure matches the plain string, keeping the scale for later operations. If \ isScientific & exp > 0 Then Do digits = digits || Copies("0", exp) exp = 0 End /* Strip trailing zeros to lowest terms WITHOUT the plain re-expansion. Used by */ /* power: (2e1)**5 becomes (32,5) and stays there. Its plain string is still */ /* 3200000, but the value keeps the higher exponent for the next operation -- */ /* faithful to ooRexx's StripResultZeros, which never re-expands. */ ::Method stripAllZeros Expose sign digits exp stringCache stringCache = .Nil Do While Length(digits) > 1 & Right(digits, 1) == "0" digits = Left(digits, Length(digits) - 1) exp = exp + 1 End ::Method withContextDigits Expose sign digits exp form Use Strict Arg newD n = .RVM.Number~new n~setState( sign, digits, exp, newD, form ) Return n /******************************************************************************/ /* Class helpers: build results with an explicit sign, apply adjustPrecision */ /* or the stripped-precision variant, and synthesise a lightweight context. */ /******************************************************************************/ /* Like fromParts, but sign is already -1/0/1 and the result is rounded to */ /* the context DIGITS (adjustPrecision). This is the common result builder. */ ::Method fromPartsSigned Class Use Strict Arg sgn, dig, ex, ctx n = .RVM.Number~new n~setState( sgn, dig, ex, ctx~digits, ctx~form ) n~adjustPrecision( ctx~digits ) Return n /* Build a result rounded to an EXPLICIT number of digits and form (used by */ /* power to prepare the base at DIGITS+1). No context object needed. */ ::Method fromPartsSignedWith Class Use Strict Arg sgn, dig, ex, nd, frm n = .RVM.Number~new n~setState( sgn, dig, ex, nd, frm ) n~adjustPrecision( nd ) Return n /* Build a result that carries its OWN precision (division, power): round to */ /* DIGITS, strip leading zeros, then drop trailing zeros before layout. */ ::Method fromPartsStripped Class Use Strict Arg sgn, dig, ex, ctx n = .RVM.Number~new n~setState( sgn, dig, ex, ctx~digits, ctx~form ) n~adjustPrecision( ctx~digits ) n~stripTrailingZeros Return n /* A lightweight NUMERIC context (digits, fuzz, form) for internal working */ /* precisions -- the Number routines run with their own NUMERIC, never the */ /* interpreted program's, so this is passed explicitly. */ ::Method ctxWith Class Use Strict Arg d, fz, frm, reporter = .Nil Return .RVM.NumCtx~new( d, fz, frm, reporter ) /******************************************************************************/ /* parseNumber : Rexx numeric string -> "sign digits exp", or "" if not a */ /* number. Sign is -1/0/1. Digits have no leading zeros (trailing kept). This */ /* is the hand-written recogniser (never DataType). */ /******************************************************************************/ ::Method parseNumber Class Use Strict Arg n Numeric Digits 20 badExp = .False n = Strip(n) If n == "" Then Return "" sgn = 1 If Left(n,1) == "-" Then Do; sgn = -1; n = Strip(Substr(n,2)); End Else If Left(n,1) == "+" Then n = Strip(Substr(n,2)) If n == "" Then Return "" -- Exponential part. ex = 0 Parse Upper Var n mantissa "E" expPart If Pos("E", Translate(Arg(1))) > 0 & expPart == "" Then Return "" -- trailing E If expPart \== "" Then Do -- expPart must be an optionally-signed whole number. ep = expPart If Left(ep,1) == "-" | Left(ep,1) == "+" Then ep2 = Substr(ep,2) Else ep2 = ep If ep2 == "" Then Return "" If ep2~verify("0123456789") \== 0 Then Return "" -- More than 9 digits: not a number (unless it is zero: see below). If Length( Strip( ep2, "L", "0" ) ) > 9 Then badExp = .True Else ex = expPart + 0 End Parse Var mantissa intPart "." fracPart -- The mantissa must be all digits in each part, and have at least one digit. If intPart \== "" & intPart~verify("0123456789") \== 0 Then Return "" If fracPart \== "" & fracPart~verify("0123456789") \== 0 Then Return "" If intPart == "" & fracPart == "" Then Return "" If intPart == "" Then intPart = "0" digs = intPart || fracPart ex = ex - Length(fracPart) digs = Strip(digs, "L", "0") If digs == "" Then Return "0 0 0" -- canonical zero -- The exponent must fit in 9 digits, and so must that of the number in -- exponential form (ooRexx's NumberStringBuilder::finish): '10E999999999' -- and '0.1E-999999999' are not numbers. If badExp Then Return "" If Abs( ex ) > 999999999 Then Return "" If ex + Length( digs ) - 1 > 999999999 Then Return "" Return sgn digs ex /******************************************************************************/ /* Magnitude mechanics (ooRexx's NumberStringMath.cpp) */ /******************************************************************************/ /* Truncate a magnitude to at most maxLen significant digits WITHOUT rounding. */ ::Method truncToMax Class Use Strict Arg dig, exp, maxLen If dig == "0" Then Return "0" exp extra = Length(dig) - maxLen If extra <= 0 Then Return dig exp Return Left(dig, maxLen) (exp + extra) /* Unsigned add of two digit strings. */ ::Method addDigits Class Use Strict Arg x, y len = Max(Length(x), Length(y)) x = Right(x, len, "0") ; y = Right(y, len, "0") carry = 0 ; result = "" Loop i = len To 1 By -1 d = Substr(x,i,1) + Substr(y,i,1) + carry If d >= 10 Then Do; d = d - 10; carry = 1; End Else carry = 0 result = d || result End If carry == 1 Then result = "1" || result Return .RVM.Number~stripLeadingZeros(result) /* Unsigned subtract y from x, assuming x >= y. */ ::Method subDigits Class Use Strict Arg x, y len = Max(Length(x), Length(y)) x = Right(x, len, "0") ; y = Right(y, len, "0") borrow = 0 ; result = "" Loop i = len To 1 By -1 d = Substr(x,i,1) - Substr(y,i,1) - borrow If d < 0 Then Do; d = d + 10; borrow = 1; End Else borrow = 0 result = d || result End Return .RVM.Number~stripLeadingZeros(result) /* Unsigned multiply of two digit strings (long multiplication, base ten). */ ::Method mulDigits Class Use Strict Arg x, y acc = "0" ; yLen = Length(y) Loop j = yLen To 1 By -1 yd = Substr(y, j, 1) If yd == 0 Then Iterate carry = 0 ; partial = "" Loop i = Length(x) To 1 By -1 p = Substr(x,i,1) * yd + carry carry = p % 10 partial = (p // 10) || partial End If carry > 0 Then partial = carry || partial partial = partial || Copies("0", yLen - j) acc = .RVM.Number~addDigits(acc, partial) End Return .RVM.Number~stripLeadingZeros(acc) /* Compare two unsigned digit strings: 1 / -1 / 0. */ ::Method compareDigits Class Use Strict Arg x, y x = .RVM.Number~stripLeadingZeros(x) y = .RVM.Number~stripLeadingZeros(y) If Length(x) \== Length(y) Then Return Sign(Length(x) - Length(y)) If x == y Then Return 0 If x >> y Then Return 1 Else Return -1 /* Compare two magnitudes aligned at their MOST significant digit (pad right). */ ::Method compareAligned Class Use Strict Arg x, y len = Max(Length(x), Length(y)) x = Left(x, len, "0") ; y = Left(y, len, "0") If x == y Then Return 0 If x >> y Then Return 1 Else Return -1 ::Method stripLeadingZeros Class Use Strict Arg s s = Strip(s, "L", "0") If s == "" Then Return "0" Return s /* The windowed subtract cascade (NumberString::subtractNumbers). Result is */ /* MSD-first, NOT stripped of leading zeros (the rounding depends on the full */ /* position count). */ ::Method subWindowed Class Use Strict Arg largerDig, adjLargerExp, smallerDig, adjSmallerExp lp = Length(largerDig) ; sp = Length(smallerDig) borrow = 0 ; res = "" Do adjLargerExp If sp >= 1 Then Do; sd = Substr(smallerDig, sp, 1) ; sp = sp - 1 ; End Else sd = 0 v = borrow + 10 - sd If v == 10 Then Do; v = 0 ; borrow = 0 ; End Else borrow = -1 res = v || res End Do adjSmallerExp If lp >= 1 Then Do; res = Substr(largerDig, lp, 1) || res ; lp = lp - 1 ; End Else res = 0 || res End Do While sp >= 1 If lp >= 1 Then Do; ld = Substr(largerDig, lp, 1) ; lp = lp - 1 ; End Else ld = 0 v = borrow + ld - Substr(smallerDig, sp, 1) ; sp = sp - 1 If v < 0 Then Do; borrow = -1 ; v = v + 10 ; End Else borrow = 0 res = v || res End Do While lp >= 1 v = borrow + Substr(largerDig, lp, 1) ; lp = lp - 1 If v < 0 Then Do; borrow = -1 ; v = v + 10 ; End Else borrow = 0 res = v || res End Return res /* Long division of magnitudes: aDig/bDig with exponents aExp/bExp, producing */ /* up to maxDigits significant quotient digits. Returns "quotientDigits scale" */ /* where scale is the exponent of the last quotient digit. (RexxDiv's loop.) */ ::Method longDivide Class Use Strict Arg aDig, aExp, bDig, bExp, maxDigits dividend = aDig ; denom = bDig scale = aExp - bExp quotient = "" ; remainder = "" pos = 0 ; sig = 0 Loop pos = pos + 1 If pos <= Length(dividend) Then nextDigit = Substr(dividend, pos, 1) Else Do nextDigit = "0" ; scale = scale - 1 End work = .RVM.Number~stripLeadingZeros( remainder || nextDigit ) q = 0 Loop d = 9 To 1 By -1 If .RVM.Number~compareDigits( .RVM.Number~mulDigits(denom, d), work ) <= 0 Then Do q = d ; Leave End End remainder = .RVM.Number~subDigits( work, .RVM.Number~mulDigits(denom, q) ) If \ (sig == 0 & q == 0) Then Do quotient = quotient || q ; sig = sig + 1 End If remainder == "0" | remainder == "" Then If pos >= Length(dividend) Then Leave If sig >= maxDigits Then Leave End Return quotient scale /******************************************************************************/ /* RVM.NumCtx -- a lightweight NUMERIC context (digits/fuzz/form) used for */ /* internal working precisions. Same read interface as RVM.BaseContext. */ /******************************************************************************/ ::Class RVM.NumCtx Public ::Attribute digits Get ::Attribute fuzz Get ::Attribute form Get ::Method init Expose digits fuzz form reporter Use Strict Arg digits, fuzz, form, reporter = .Nil -- Working precisions are internal: a longer operand there is not LOSTDIGITS, -- unless the working context stands for the program's own arithmetic at a -- reduced precision (a comparison under FUZZ), which reports to 'reporter'. ::Method lostDigits Expose reporter Use Strict Arg n If reporter \== .Nil Then reporter~lostDigits( n ) /******************************************************************************/ /* The boundary routines num() and str() (doc/02-values-and-arithmetic.md) */ /* */ /* num(v, ctx) : ensure v is a Number. A Number passes through; a string is */ /* parsed (error 41 if not numeric), recording the context */ /* NUMERIC settings. */ /* str(v) : ensure v is a string. A Number is serialised (lazy); a */ /* string passes through unchanged. */ /* */ /* These are the ONLY places Evaluate crosses between the two representations. */ /******************************************************************************/ ::Routine num Public Use Strict Arg v, ctx If v~isA(.RVM.Number) Then Return v -- Any other object (an RVM object): its string value. If \ v~isA(.String) Then v = str(v) n = .RVM.Number~fromString( v, ctx ) If n == .Nil Then Do -- The value as it is (blanks included). An empty insert would not be -- substituted by RAISE, so that message is given in full. If v == "" Then Raise Syntax 41.900 Array( "", .Array~of( "" ) ) Description( - 'RVM.Message 41.1 Nonnumeric value ("") used in arithmetic operation.' ) Raise Syntax 41.1 Additional( v ) End Return n ::Routine str Public Use Strict Arg v If v~isA(.String) Then Return v If .Nil == v Then Return v If v~isA(.RVM.Number) Then Return v~string -- An object of the RVM: its string value (which may need its STRING -- method to run: see RVM.Obj); any other object, its string. If v~hasMethod( "STRINGVALUE" ) Then Return v~stringValue Return v~string /* wholeNumber(v, d) / unsignedWholeNumber(v, d) : numberValue and */ /* unsignedNumberValue for any value, Number or string. A string that is not */ /* a number is simply not a whole number (.Nil): the caller raises its OWN */ /* error (26.8 for a ** exponent, the argument error for a built-in function), */ /* never 41. Any other object (an RVM object): its string value, as num. */ ::Routine wholeNumber Public Use Strict Arg v, numDigits v = StemValue( v ) If \ v~isA(.RVM.Number) Then Do v = .RVM.Number~fromString( str( v ) ) If v == .Nil Then Return .Nil End Return v~numberValue( numDigits ) /* nativeWhole(v) : a whole number argument of a native routine (ooRexx's */ /* Numerics::objectToSignedInteger: int64Value at SIZE_DIGITS, 20 -- digits */ /* past the 20th are truncated, with their carry, and the decimals left must */ /* be zeros; no rounding to 18), within MAX_WHOLENUMBER (18 nines); else */ /* .Nil. */ ::Routine nativeWhole Public Use Strict Arg v w = wholeNumber( v, 20 ) If w == .Nil Then Return .Nil Numeric Digits 20 If Abs( w ) > 999999999999999999 Then Return .Nil Return w ::Routine unsignedWholeNumber Public Use Strict Arg v, numDigits v = StemValue( v ) If \ v~isA(.RVM.Number) Then Do v = .RVM.Number~fromString( str( v ) ) If v == .Nil Then Return .Nil End Return v~unsignedNumberValue( numDigits ) /* StemValue(v) : a Stem object's value (its default, as ooRexx's StemClass */ /* numberValue and unsignedNumberValue give: no string conversion, and so no */ /* NOSTRING); anything else, itself. */ ::Routine StemValue Public Use Strict Arg v -- (By name: this package does not see RVM.Objects.) Loop While v~class~id == "RVM.OBJ" If v~native~class~id \== "RVM.STEM" Then Leave v = v~native~value End Return v /* isNum(v) : is v a number? A Number always is; a string is if it parses. */ /* Used to decide numeric vs string comparison, replacing DataType(v,"N"). */ ::Routine isNum Public Use Strict Arg v If v~isA(.RVM.Number) Then Return 1 Return .RVM.Number~parseNumber( str( v ) ) \== "" /* lit(source, ctx) : evaluate a numeric LITERAL. A whole-number literal that */ /* fits under min(DIGITS,18) is "born Integer" (ooRexx's RexxInteger), */ /* carrying its own text (007 stays 007). Anything with a point or exponent, */ /* or too wide to fit as a whole, is a plain Number. The literal is always */ /* valid (the parser only classified it as a number), so num() semantics for */ /* errors do not apply. */ ::Routine lit Public Use Strict Arg source, ctx -- "Born Integer" is a SYNTACTIC property of the literal TEXT, not its value: -- 1000 and 007 are integer literals, but 1e3 and 1.5 are not (they carry an -- exponent or a point), even though 1e3 has an integer value. ooRexx builds a -- RexxInteger only for the digits-only form, so 1e3 stays NumberString and -- 1e3*1.5 keeps its exponent structure. t = Strip( source ) If Left(t, 1) == "+" | Left(t, 1) == "-" Then t = Substr(t, 2) digitsOnly = ( t \== "" & t~verify("0123456789") == 0 ) -- Pass the raw signed text as the whole; initInteger normalises it at high -- host precision (source/1 here would round an 18-digit literal at DIGITS 9). If sgn( source ) < 0 Then signed = "-" || t Else signed = t If digitsOnly & Length( Strip(t, "L", "0") ) <= .RVM.Integer~MAXWHOLEDIGITS Then Return .RVM.Integer~fromWhole( signed, ctx, .RVM.Number~canonLiteral(source) ) -- A constant symbol that ooRexx does not take as a number (its exponent -- out of range: 0.1E-999999999) is a string, its name (upper case). n = .RVM.Number~fromString( source, ctx ) If n == .Nil Then Return Upper( source ) Return n /* ExactAddSub: plus and minus when both operands are non-zero and, aligned */ /* at the smaller exponent (minExp), have at most DIGITS digits. Then addSub */ /* truncates nothing (its window is DIGITS+1), takes neither of its */ /* magnitude-gap exits, and builds the exact sum or difference of the aligned */ /* magnitudes at minExp (both of its branches: rExp is minExp), rounded by */ /* fromPartsSigned; zero is (0, "0", 0). The same result, computed by the */ /* host at DIGITS+2 (exact for two numbers of DIGITS digits). No LOSTDIGITS */ /* either: neither operand is longer than DIGITS. bSign is already negated */ /* for minus. */ ::Routine ExactAddSub Use Arg aSign, aDig, aExp, bSign, bDig, bExp, minExp, ctx d = ctx~digits Numeric Digits d + 2 a = aDig || Copies( "0", aExp - minExp ) b = bDig || Copies( "0", bExp - minExp ) If aSign < 0 Then a = "-" || a If bSign < 0 Then b = "-" || b r = a + b If r = 0 Then Return .RVM.Number~fromPartsSigned( 0, "0", 0, ctx ) If r < 0 Then Return .RVM.Number~fromPartsSigned( -1, Substr( r, 2 ), minExp, ctx ) Return .RVM.Number~fromPartsSigned( 1, r, minExp, ctx ) /* The exponent part of a number in exponential form: "E+n", "E-n", or nothing */ /* at all when the exponent is zero (ENGINEERING can shift it to 0: at DIGITS 2 */ /* 344.7 is 340, not 340E+0). */ ::Routine ExpSuffix Private Use Strict Arg e If e > 0 Then Return "E+" || e If e < 0 Then Return "E-" || Abs(e) Return "" /* Sign of a literal's text: -1 if it starts with '-', else 1. */ ::Routine sgn Private Use Strict Arg s If Left( Strip(s), 1 ) == "-" Then Return -1 Return 1 /******************************************************************************/ /* */ /* RVM.Integer -- a Number whose value is a whole number that "fits". */ /* ========================================================== */ /* */ /* This is the SPEED subclass. It carries a native whole number and does each */ /* arithmetic operation with the host's own integer math when both operands */ /* fit under the current DIGITS and the result fits too -- exactly ooRexx's */ /* RexxInteger fast path (IntegerClass.cpp). When any of that fails, it */ /* forwards to the Number (NumberString) method by inheritance, so the result */ /* is bit-for-bit identical to the Number's. */ /* */ /* "Fits" = Numerics::isValid: |v| <= 10^min(DIGITS,18) - 1, tested per */ /* operation on both operands AND the result, against the CURRENT digits (not */ /* a property of the value). */ /* */ /* Golden rule: an Integer and a Number of the same whole value are */ /* INDISTINGUISHABLE from outside. The only observable differences come from */ /* the places ooRexx forwards ON PURPOSE (e.g. n**2, which '**' strips and */ /* '*' does not): those are reproduced by forwarding here too. */ /* */ /* The base Number fields (sign/digits/exp/createdDigits/form) are */ /* materialised from the whole at construction, so every inherited Number */ /* method works unchanged; the whole is kept alongside for the fast paths. */ /******************************************************************************/ ::Class RVM.Integer Subclass RVM.Number Public -- The largest number of digits a native whole may have: WholeDigits. ::Method MAXWHOLEDIGITS Class Return .RVM.Number~WholeDigits ::Attribute whole Get -- the native integer value (a Rexx whole-number string) ::Attribute whole Set Private ::Attribute text Get Private -- optional original literal text (007) ::Attribute text Set Private /* fromWhole(v, ctx [, text]) : build an Integer from a native whole number. */ /* Materialises the base fields from v and records the current NUMERIC state. */ ::Method fromWhole Class Use Strict Arg v, ctx, txt = .Nil If ctx == .Nil Then Do d = 9 ; f = "SCIENTIFIC" End Else Do d = ctx~digits ; f = ctx~form End n = .RVM.Integer~new n~initInteger( v, d, f, txt ) Return n /* Populate whole + base fields (sign/digits/exp) + createdDigits/form/text. */ ::Method initInteger Expose whole text Use Strict Arg v, d, f, txt Numeric Digits 40 -- host precision for the setup only v = v / 1 -- normalise (strip +, leading zeros) whole = v text = txt If v == 0 Then self~setState( 0, "0", 0, d, f ) Else Do If v < 0 Then sgn = -1 Else sgn = 1 dig = Abs(v)~string -- Trailing zeros of a whole are scale (exp 0 keeps them): 3200000 stays -- (3200000, 0), matching ooRexx's Integer (not the stripped NumberString). self~setState( sgn, dig, 0, d, f ) End -- If a literal text was given, it is the string value (007 stays 007). If txt \== .Nil Then self~setCacheProtected( txt ) /* setCacheProtected : expose the base's private cache setter to this subclass. */ ::Method setCacheProtected Use Strict Arg s self~setCache( s ) /* validWhole(v, d) : does the whole v fit under d digits? |v| <= 10^min(d,18) */ /* - 1, i.e. |v| has at most min(d,18) digits. Counted on the STRING (no Abs/ */ /* arithmetic, which would round a >9-digit v at this method's own DIGITS 9). */ ::Method validWhole Class Use Strict Arg v, d lim = Min(d, .RVM.Integer~MAXWHOLEDIGITS) av = v~string If Left(av, 1) == "-" | Left(av, 1) == "+" Then av = Substr(av, 2) av = Strip(av, "L", "0") If av == "" Then av = "0" -- v was zero Return Length(av) <= lim /******************************************************************************/ /* Fast-path operators. Each mirrors IntegerClass.cpp: try native math when */ /* both operands are Integers valid under DIGITS and the result fits; else */ /* forward to the Number method by inheritance (self~op:super), which is the */ /* NumberString path and gives the Number's result. */ /******************************************************************************/ ::Method plus Expose whole Use Strict Arg other, ctx d = ctx~digits If .RVM.Integer~validWhole(whole, d) & other~isA(.RVM.Integer) Then Do ov = other~whole If .RVM.Integer~validWhole(ov, d) Then Do Numeric Digits 40 result = whole + ov If .RVM.Integer~validWhole(result, d) Then Return .RVM.Integer~fromWhole( result, ctx ) End End Return self~plus:super( other, ctx ) ::Method minus Expose whole Use Strict Arg other, ctx d = ctx~digits If .RVM.Integer~validWhole(whole, d) & other~isA(.RVM.Integer) Then Do ov = other~whole If .RVM.Integer~validWhole(ov, d) Then Do Numeric Digits 40 result = whole - ov If .RVM.Integer~validWhole(result, d) Then Return .RVM.Integer~fromWhole( result, ctx ) End End Return self~minus:super( other, ctx ) ::Method times Expose whole Use Strict Arg other, ctx d = ctx~digits If .RVM.Integer~validWhole(whole, d) & other~isA(.RVM.Integer) Then Do ov = other~whole If .RVM.Integer~validWhole(ov, d) Then Do -- shortcuts (ooRexx multiply): 0, 1, -1 handled by general path fine. Numeric Digits 40 result = whole * ov If .RVM.Integer~validWhole(result, d) Then Return .RVM.Integer~fromWhole( result, ctx ) End End Return self~times:super( other, ctx ) ::Method divide Expose whole Use Strict Arg other, ctx d = ctx~digits If .RVM.Integer~validWhole(whole, d) & other~isA(.RVM.Integer) Then Do ov = other~whole If .RVM.Integer~validWhole(ov, d) & ov \== 0 Then Do -- '/' is done in binary ONLY when the division is EXACT (no remainder); -- otherwise NumberString handles the fractional quotient. Numeric Digits 40 If whole // ov == 0 Then Return .RVM.Integer~fromWhole( whole % ov, ctx ) End End Return self~divide:super( other, ctx ) ::Method intDivide Expose whole Use Strict Arg other, ctx d = ctx~digits If .RVM.Integer~validWhole(whole, d) & other~isA(.RVM.Integer) Then Do ov = other~whole If .RVM.Integer~validWhole(ov, d) & ov \== 0 Then Do Numeric Digits 40 Return .RVM.Integer~fromWhole( whole % ov, ctx ) End End Return self~intDivide:super( other, ctx ) ::Method remainder Expose whole Use Strict Arg other, ctx d = ctx~digits If .RVM.Integer~validWhole(whole, d) & other~isA(.RVM.Integer) Then Do ov = other~whole If .RVM.Integer~validWhole(ov, d) & ov \== 0 Then Do Numeric Digits 40 Return .RVM.Integer~fromWhole( whole // ov, ctx ) End End Return self~remainder:super( other, ctx ) ::Method power Expose whole Use Strict Arg other, ctx d = ctx~digits -- n ** 2 forwards ON PURPOSE (** strips trailing zeros, * does not), so we -- do NOT fast-path a square. Only whole exponents in [0..MaxPower], base -- not zero-special, and the exact result must fit. If .RVM.Integer~validWhole(whole, d) & other~isA(.RVM.Integer) Then Do p = other~whole If .RVM.Integer~validWhole(p, d) & p >= 0 & p \== 2 Then Do Numeric Digits 40 -- Compute whole ** p exactly and check it fits under DIGITS. result = 1 ok = 1 Do p result = result * whole If Length(Abs(result)~string) > .RVM.Integer~MAXWHOLEDIGITS Then Do ok = 0 ; Leave End End If ok & .RVM.Integer~validWhole(result, d) Then Return .RVM.Integer~fromWhole( result, ctx ) End End Return self~power:super( other, ctx ) ::Method negate Expose whole Use Strict Arg ctx d = ctx~digits If .RVM.Integer~validWhole(whole, d) Then Do Numeric Digits 40 Return .RVM.Integer~fromWhole( -whole, ctx ) End Return self~negate:super( ctx ) /* identity : prefix '+'. An Integer with no literal text and matching NUMERIC */ /* returns self; otherwise it normalises like the base (which drops a literal). */ ::Method identity Expose whole text Use Strict Arg ctx If text == .Nil & self~createdDigits == ctx~digits & self~form == ctx~form Then Return self Return self~identity:super( ctx ) ::Method compare Expose whole Use Strict Arg other, ctx -- Binary compare only when both fit AND FUZZ = 0; else the base handles it. If .RVM.Integer~validWhole(whole, ctx~digits) & other~isA(.RVM.Integer) & ctx~fuzz == 0 Then Do ov = other~whole If .RVM.Integer~validWhole(ov, ctx~digits) Then Do Numeric Digits 40 diff = whole - ov If diff == 0 Then Return 0 If diff < 0 Then Return -1 Return 1 End End Return self~compare:super( other, ctx )