What is inf and nan?

前端 未结 5 723
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-28 11:57

Just a question that I\'m kind of confused about

So I was messing around with float(\'inf\') and kind of wondering what it is used for.

Also I n

相关标签:
5条回答
  • 2020-12-28 12:46

    I use inf/-inf as initial values to find minimum/maximum value of a measurement. Lets say that you measure temperature with a sensor and you want to keep track of minimum/maximum temperature. The sensor might provide a valid temperature or might be broken. Pseudocode:

    # initial value of the temperature
    t = float('nan')          
    # initial value of minimum temperature, so any measured temp. will be smaller
    t_min = float('inf')      
    # initial value of maximum temperature, so any measured temp. will be bigger
    t_max = float('-inf')     
    while True:
        # measure temperature, if sensor is broken t is not changed
        t = measure()     
        # find new minimum temperature
        t_min = min(t_min, t) 
        # find new maximum temperature
        t_max = max(t_max, t) 
    

    The above code works because inf/-inf/nan are valid for min/max operation, so there is no need to deal with exceptions.

    0 讨论(0)
  • 2020-12-28 12:47

    You say:

    when i do nan - inf i dont get -inf i get nan

    This is because any operation containing NaN as an operand would return NaN.

    A comparison with NaN would return an unordered result.

    >>> float('Inf') == float('Inf')
    True
    >>> float('NaN') == float('NaN')
    False
    
    0 讨论(0)
  • 2020-12-28 12:47

    Inf is infinity, it's a "bigger than all the other numbers" number. Try subtracting anything you want from it, it doesn't get any smaller. All numbers are < Inf. -Inf is similar, but smaller than everything.

    NaN means not-a-number. If you try to do a computation that just doesn't make sense, you get NaN. Inf - Inf is one such computation. Usually NaN is used to just mean that some data is missing.

    0 讨论(0)
  • 2020-12-28 12:48

    nan means "not a number", a float value that you get if you perform a calculation whose result can't be expressed as a number. Any calculations you perform with NaN will also result in NaN.

    inf means infinity.

    For example:

    >>> 2*float("inf")
    inf
    >>> -2*float("inf")
    -inf
    >>> float("inf")-float("inf")
    nan
    
    0 讨论(0)
  • 2020-12-28 12:51

    inf is infinity - a value that is greater than any other value. -inf is therefore smaller than any other value.

    nan stands for Not A Number, and this is not equal to 0.

    Although positive and negative infinity can be said to be symmetric about 0, the same can be said for any value n, meaning that the result of adding the two yields nan. This idea is discussed in this math.se question.

    Because nan is (literally) not a number, you can't do arithmetic with it, so the result of the second operation is also not a number (nan)

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