Express mathematical infinity in C#
-
20-09-2019 - |
Question
Is it possible to express (mathematical) infinity, positive or negative, in C#? If so, how?
Solution
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"
OTHER TIPS
Use the PositiveInfinity
and NegativeInfinity
constants:
double positive = double.PositiveInfinity;
double negative = double.NegativeInfinity;
public const double NegativeInfinity = -1.0 / 0.0;
public const double PositiveInfinity = 1.0 / 0.0;
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.
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