Here's a weird calculation error in VB.NET. I've simplified my problem to the following. I can write:
Console.WriteLine(-0.78125 ^ 2.5)
and get -0.53947966093944366
.
But if I change it to Console.WriteLine((-0.78125 + 0) ^ 2.5)
, I get -1.#IND
.
Or, if it try:
Dim D as Double = -0.78125
Console.WriteLine(D ^ 2.5)
I also get -1.#IND
.
I can only get the calculation to return a result if I use a single literal number in the expression, but when I use a variable of any data type I get -1.#IND
.
I've read the other posts that explaining "-1.#IND", but they indicate that one of the numbers in the expression is NaN, which is not the case here. Why is this happening?
strange adjective (UNUSUAL)unusual and unexpected, or difficult to understand: He has some very strange ideas about women! You say the strangest things sometimes. I had a strange feeling that we'd met before.
Anything that is unusual or out of the ordinary can be described as strange, like the strange sight of an ice cream truck pulling up in front of your school and your principal skipping over to it.
adjective. /streɪndʒ/ (stranger, strangest) 1unusual or surprising, especially in a way that is difficult to understand A strange thing happened this morning.
You can figure out what's going on by trying following:
Console.WriteLine(-1 ^ 0.5)
It prints -1
, but in fact it is the same as sqrt(-1)
which does not have a result in Real numbers. That's weird, isn't it? So what's going on here?
^
has higher precedence than -
, so -1 ^ 0.5
is actually -(1 ^ 0.5)
. That's why it prints -1
.
You can check the precedence list here: Operator Precedence in Visual Basic
The same happens with your code. -0.78125 ^ 2.5
is actually interpreted as -(0.78125 ^ 2.5)
which is valid, but if you do (-0.78125 + 0) ^ 2.5
(or even (-0.78125) ^ 2.5
) it's not valid anymore, because it would require calculating square root from negative value. That's why you're getting NaN
(or -1#IND
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With