henshiro64
henshiro64

Reputation: 121

c# how to check if a number is infinity

i have a little problem. I have two double variables which each has the value 1*10^250. Now if I multiplicate these two values I get a result which is also a double variable. The problem is that the result of the multiplication gives me the value infinity but I want to prevent this and give an error message. So it would be nice if someone know how to identify if a number is infinity.

Upvotes: 11

Views: 23262

Answers (5)

Steve Nyholm
Steve Nyholm

Reputation: 906

To compliment the high voted answers, here's a quick code snippet to demonstrate their usage.

double d1 = Math.Pow(10, 250); // = 1*10^250
double d2 = Math.Pow(10, 250);
double d3 = d1 * d2; 

Console.WriteLine (d1);
Console.WriteLine (d2);
Console.WriteLine (d3);

Console.WriteLine (Double.IsInfinity(d3)); //true (using a method)
Console.WriteLine (d3 == Double.PositiveInfinity); //true (comparing to a value)
Console.WriteLine (d3 == double.PositiveInfinity); //true (note that "Double" or "double" can be used)

Console.WriteLine (d3 == Double.NaN); //false
Console.WriteLine (d3 == Double.MaxValue); //false

Upvotes: 1

dancer42
dancer42

Reputation: 189

use

double.IsInfinity(theDoubleNumber);

you can also use double.IsNegativeInfinity(), double.IsPositiveInfinity(), double.NaN(), double.MaxValue(), double.MinValue() for similar purpose

Upvotes: 9

Sudhakar singh
Sudhakar singh

Reputation: 104

try this..

if (Double.IsInfinity(SampleVar))
{
  // Put your logic here.
}
if (Double.IsNaN(SampleVar))
{
  // Put your logic here.
}

Upvotes: 2

Viezevingertjes
Viezevingertjes

Reputation: 1577

How about the Double.IsInfinity(Double) method?

Double.IsInfinity(3.0 / 0)

See also

Upvotes: 21

Nicolas
Nicolas

Reputation: 71

It is enough to extract the logarithms of the 2 variables and then to add them. Simplyt before you multiply to catch the error, if the variables to be multiplied are A and B follow this pseudo-code :

#include <math.h>
Double A,B,L1,L2;
Boolean MYERROR;
main(){
L1 = LOG10(A);
L2 = LOG10(B);
If( (L1 + L2) > DBL_MAX_10_EXP){ MYERROR = true;}else{MYERROR = false;}
}

Upvotes: -3

Related Questions