Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange -1.#IND error in VB.NET

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?

like image 882
user2759614 Avatar asked Sep 08 '13 20:09

user2759614


People also ask

What is the mean of strange?

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.

What is strange example?

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.

What is the meaning of strange in Oxford dictionary?

adjective. /streɪndʒ/ (stranger, strangest) 1unusual or surprising, especially in a way that is difficult to understand A strange thing happened this morning.


1 Answers

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).

like image 143
MarcinJuraszek Avatar answered Sep 21 '22 22:09

MarcinJuraszek