Search code examples
luadoublepow

Why does ZeroBrane studio evaluates "^" as not a number when the power is a double


Well as it generally says, I have the following situation. I wrote a "main.lua" file, which includes the other file with an object definition having the following method:

  function self:Process(vRef,vOut,bNeg)
    mErrO = mErrN
    mErrN = (bNeg and (vOut-vRef) or (vRef-vOut)) -- Refresh error state
    logStatus(nil,"MER= "..mErrO.." > "..mErrN)
    local errS  = getSign(mErrN)
    -- P-Term
    logStatus(nil,"S P: >> "..tostring(errS))
    local errP = mErrN;          logStatus(nil,"0 P: >> "..tostring(errP))
          errP = errP^mpP;       logStatus(nil,"1 P: >> "..tostring(errP))
          errP = math.abs(errP); logStatus(nil,"2 P: >> "..tostring(errP))
          errP = errP*errS;      logStatus(nil,"3 P: >> "..tostring(errP))

As you all may see, if we have like (-198^1.01), the result must be ( respectively ) (-208.75257542111). I added the following line in the "main.lua" file:

local a = (-198^1.01)
local b = ( 198^1.01)
local c = ( 0^1.01)

logStatus(nil,"-------------Pow: {"..a..","..b..","..c.."}")

However, these are calculated correctly. I thin it is somehow related by the object and the fact that the ZeroBrane must be using an older version of Lua. Strangely when the power argument is 1,2,3,4 ... It works fine. The program output is as follows:

-------------Pow: {-208.75257542111,208.75257542111,0}
MER= 0 > -198
S P: >> -1
0 P: >> -198
1 P: >> nan
2 P: >> nan
3 P: >> nan

Any answer will be appreciated !


Solution

  • In your first code

    local errP = mErrN;     -->  -198
          errP = errP^mpP;  -->  nan
    

    the expression being calculated is (-198)^1.01.
    It is nan according to math definition of raising to power and according to the man page of pow():

    pow(x, y) returns a NaN and raises the "invalid" floating-point exception for finite x < 0 and finite non-integer y.

    In your second code

    local a = (-198^1.01)
    

    the expression is -(198^1.01) according to Lua operators precedence.
    This expression equals to -208.75...


    Probably you would want to calculate math.abs(x)^y * (x<0 and -1 or 1) instead of x^y