Monday, April 21, 2008

Dealing with infinite and indeterminate values in C++

In my programs infinity usually arises when a value is divided by zero. I get indeterminate when I divide zero by zero.

In C++, infinity is represented by 1.#INF. Indeterminate is represented by -1.#IND. The problem is how to test if a variable is infinite or indeterminate. Checking infinity is relatively straightforward: You find the infinity definition in your particular C++. For my case (VS2003), it is std::numeric_limits::infinity(). You have to include "limits" in order to use it. You can assign this infinite value to a variable and you can compare it to some value in order to check if that value is infinite.

Indeterminate is a little tricky, because you cannot compare an indeterminate value to some other value. Any comparison returns false. You can use this property to detect an indeterminate value by comparing it to itself. Let's say you have a double variable called aVal. Under normal conditions, aVal != aVal returns false. But if aVal is indeterminate, aIndVal != aIndVal returns true. This weird situation is not present for infinite values, i.e. aInfVal != aInfVal always returns false.

Here are two functions that can be used to check for indeterminate and infinite values:


Update Jan 04, 2009: I asked this question on Stackoverflow

3 comments:

Rahmi Lale said...

Haji, bu yazı yeni olmasına karşın ana sayfada ilk değil de 3. yazı olarak görünüyor.

Draft yazılmış yazılar yayımlanınca böyle bir sorun oluyor sanırsam?

Aruna Jayaraman said...

Life Saver!. Thanks a bunch man!

Anonymous said...

You have tested it and writing form your personal experience or you find some information online?