views:

1003

answers:

4

Is it possible to express (mathematical) infinity, positive or negative, in C#? If so, how?

+4  A: 
public const double NegativeInfinity = -1.0 / 0.0;
public const double PositiveInfinity = 1.0 / 0.0;
ChaosPandion
+12  A: 

double.PositiveInfinity

double.NegativeInfinity

float zero = 0;

float positive = 1 / zero;
Console.WriteLine(positive);    // Outputs "Infinity"

float negative = -1 / zero;
Console.WriteLine(negative);    // Outputs "-Infinity"
Jaimal Chohan
why didn't you just do float positive = 1/0;? why the extra step
hhafez
Becuase the compiler will detect the divide by zero and stop compilation.
Jaimal Chohan
@Jaimal: That's because the compiler treats `1/0` as integer division. Using `1/0f` or `1/0.0` would work.
LukeH
@Luke: Ahh of course.
Jaimal Chohan
+2  A: 

Yes, check constants values of types float and double, like:
float.PositiveInfinity
float.NegativeInfinity
Those values are compliant with IEEE-754, so you might want to check out how this works exactly, so you will be aware, when and how you can get those values while making calculations. More info here.

Ravadre
+3  A: 

Use the PositiveInfinity and NegativeInfinity constants:

double positive = double.PositiveInfinity;
double negative = double.NegativeInfinity;
Jeff L