Error with 'loadstring' finding even powers of negative numbers

Hello,
I ran into an issue recently where when you find a negative number to the power of 2 (in example), the result will be negative. Here is my example to prove it:

function setup()
    for i = -10,10 do
        local computedNormally = i^2
        local computedDynamically = loadstring("return "..i.."^2")()
        print("i: "..i.."\
Normally computed math: "..computedNormally.."\
Computed using 'loadstring': "..computedDynamically)
    end
end

I’m doing a temporary fix by simply making it positive if the input is negative.

Thank you!

I don’t know why… but you can use math.pow if you need.

@Zoyt adding parenthesis around i solves it for loadstring. But you are right, it is annoying. On the other hand, the notation -1^2 is ambiguous:is it (-1)^2 or -(1^2)?

Actually all of this is correct. A negative number such as -5^2 is -25. You need to look up order of operation for math functions. The ^ (power) has a higher order than - (minus). So in the example -5^2 means it takes 5^2 first making it 25. Then the - comes next making it -25. The () have an even higher order then ^, so in (-5)^2, it makes 5 negative before it squares it, making the answer 25.

@dave1707 - I thought of that right as I went offline. You’re right. I’ll just put parenthesis around it.
Thanks!

See, maths is important!

@Andrew_Stacey - Remember, eats, shoots, and leaves. (It’s math’s.) :wink:
But thanks. :slight_smile:

@Zoyt. I wrote:

“maths is important”

No apostrophe needed there. Where do you see the need for one?

@Andrew_Stacey, I agree there is no need for one, but couldn’t it be written as “math’s important”?

@JakAttak But then it would be “maths’s important” which is just weird.

@Andrew_Stacey You don’t put an S after the apostrophe if the word ended with S before, but you pronounce it with an S on the end. It would be maths’. Still looks kinda weird, though…

@SkyTheCoder That’s the rule for the possessive pronoun. This is a contractive apostrophe. I don’t know if one would ever contract a word ending in ‘s’ with ‘is’ as it doesn’t sound any different.

@Andrew_Stacey, wouldn’t it be math is important and not maths is important in the first place? Or if it were maths, shouldn’t it be maths are important?

@JakAttak Both math (US) and maths (UK) are abbreviations for mathematics which is almost always used as a singular noun. So whether you are American and say math is important or British and say maths is important, the verb will be the same in either phrase as both are abbreviated forms of mathematics is important.

(For a word to compare with, consider dynamics. You can say the dynamics of the machine were complicated or dynamics is an important topic in physics. The word mathematics is almost always used in the second sense, not the first.)

@Andrew_Stacey - That makes more sense. You were using the UK abbreviation, I assume?

@Zoyt, well, I am British, after all.