Alex
Alex

Reputation: 77329

Express mathematical infinity in C#

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

Upvotes: 31

Views: 35946

Answers (5)

Amin Saadati
Amin Saadati

Reputation: 133

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

Upvotes: 1

Jeff L
Jeff L

Reputation: 6188

Use the PositiveInfinity and NegativeInfinity constants:

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

Upvotes: 44

Marcin Deptuła
Marcin Deptuła

Reputation: 11957

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.

Upvotes: 6

Jaimal Chohan
Jaimal Chohan

Reputation: 8645

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"

Upvotes: 34

ChaosPandion
ChaosPandion

Reputation: 78272

public const double NegativeInfinity = -1.0 / 0.0;
public const double PositiveInfinity = 1.0 / 0.0;

Upvotes: 5

Related Questions