30

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

Alex
  • 75,813
  • 86
  • 255
  • 348

5 Answers5

44

Use the PositiveInfinity and NegativeInfinity constants:

double positive = double.PositiveInfinity;
double negative = double.NegativeInfinity;
Jeff L
  • 6,108
  • 3
  • 23
  • 29
34

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
  • 8,530
  • 6
  • 43
  • 64
6

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.

Marcin Deptuła
  • 11,789
  • 2
  • 33
  • 41
5
public const double NegativeInfinity = -1.0 / 0.0;
public const double PositiveInfinity = 1.0 / 0.0;
ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
1

look this (just return Positive-infinity ∞)

Remarks :

The value of this constant is the result of dividing a positive number by zero. This constant is returned when the result of an operation is greater than MaxValue. Use IsPositiveInfinity to determine whether a value evaluates to positive infinity.

So this will equal Infinity.

Console.WriteLine("PositiveInfinity plus 10.0 equals {0}.", (Double.PositiveInfinity + 10.0).ToString());

and now for negative is

This constant is returned when the result of an operation is less than MinValue.

so this will equal Infinity.

Console.WriteLine("10.0 minus NegativeInfinity equals {0}.", (10.0 - Double.NegativeInfinity).ToString());

reference : https://msdn.microsoft.com/en-us/library/system.double.negativeinfinity(v=vs.110).aspx

Amin Saadati
  • 133
  • 8