问题
How can I represent -infinity
in C++, Java, etc.?
In my exercise, I need to initialize a variable with -infinity
to show that it's a very small number.
When computing -infinity - 3
, or -infinity + 5
it should also result -infinity
.
I tried initializing it with INT_MIN
, but when I compute INT_MIN - 1
I get the upper limit, so I can't make a test like: if(value < INT_MIN) var = INT_MIN;
So how can I do that?
回答1:
You could define a number as -infinite and, when adding or substracting something from a number, you do first check if the variable was equal to that pseudo-number. If so you just leave it as it was.
But you might find library functions giving you that functionality implemented, e.g Double in Java or std in c++.
回答2:
You cannot represent infinity with integers[1]. However, you can do so with floating point numbers, i.e., float
and double
.
You list several languages in the tags, and they all have different ways of obtaining the infinity value (e.g., C99 defines INFINITY
in math.h
, if infinity is available with that implementation, while Java has POSITIVE_INFINITY
and NEGATIVE_INFINITY
in Float
and Double
classes). It is also often (but not always) possible to obtain infinity values by dividing floating point numbers by zero.
[1] Excepting the possibility that you could wrap every arithmetic operation on your integers with code that checks for a special value that you treat as infinity. I wouldn't recommend this.
回答3:
You can have -Infinity
as a floating point literal (at least in Java):
double negInf = Double.NEGATIVE_INFINITY;
It is implemented according to the IEEE754 floating point spec.
回答4:
If there was the possibility that a number was not there, instead of picking a number from its domain to represent 'not there', I would pick a type with both every integer I care about, and a 'not there' state.
A (deferred) C++1y proposal for optional
is an example of that: an optional<int>
is either absent, or an integer. To access the integer, you first ask if it is there, and if it is you 'dereference' the optional to get it.
Making infectious optionals: ones that, on almost any binary operation, infect the result if either value is absent, should be an easy extension of this idea.
回答5:
If you want to represent the minimum value you can use, for example
for integers
int a = Integer.MIN_VALUE;
and floats, doubles, etc take each object wrapper min value
回答6:
You can't truly represent an infinite value because you've got to store it in a finite number of bits. There are symbolic versions of infinity in certain types (e.g. in the typical floating point specification), but it won't behave exactly like infinity in the strict sense. You'll need to include some additional logic in your program to emulate the behaviour you need.
来源:https://stackoverflow.com/questions/19859838/how-to-represent-infinity-in-programming