View Full Version : Raising a negative number to a power
paravantis
27-08-2024, 12:23
It appears that the use of parentheses in the following code gives an invalid delimiter error
Uses "Console"
printl (-2)^2
WaitKey
while the following alternative runs well
Uses "Console"
printl -2^2
WaitKey
On the other hand, the following version gives the wrong answer!
Uses "Console"
printl -(2)^2
WaitKey
So, something is not right with parsing such numerical expressions.
ErosOlmi
27-08-2024, 20:45
Problem is in PRINTL
It assumes that the expression to print is a string so parsing consider it as a string and not a number
Try this where I've included your numeric expressions into STR$(...) that assumes to parse a number and convert into a string
Uses "Console"
printl "(-2)^2 =", str$((-2)^2)
printl "-2^2 =", str$(-2^2)
printl "-(2)^2 =", str$(-(2)^2)
WaitKey
thinBasic is a real-time interpreter without any intermediate code.
String parsing try to look ahead to check if next expression can be a numeric expression and not a string, switch into numeric parsing and at the end covert into a string.
But seems there is something to improve here.
Will have a look
Thanks
ErosOlmi
27-08-2024, 21:15
Interesting :D
Excel gives 4
Calc gives 4
Google gives -4 but because it transform -(2)^2 into -(2^2) and that gives -4 also in all other programs thinBasic included
paravantis
27-08-2024, 21:24
Like you have suggested here and in older posts, I am going to be using
Tstr$(numeric expression)
and plenty of parentheses everywhere, to be on the safe side.