How to represent -infinity in programming

前端 未结 6 1726
野趣味
野趣味 2021-01-17 01:18

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

相关标签:
6条回答
  • 2021-01-17 01:34

    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.

    0 讨论(0)
  • 2021-01-17 01:38

    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.

    0 讨论(0)
  • 2021-01-17 01:48

    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.

    0 讨论(0)
  • 2021-01-17 01:53

    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++.

    0 讨论(0)
  • 2021-01-17 01:53

    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.

    0 讨论(0)
  • 2021-01-17 01:54

    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

    0 讨论(0)
提交回复
热议问题