Python division

前端 未结 12 1013
挽巷
挽巷 2020-11-21 06:23

I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evalu

相关标签:
12条回答
  • 2020-11-21 06:45

    You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.

    >>> 1 / 2
    0
    

    You should make one of them a float:

    >>> float(10 - 20) / (100 - 10)
    -0.1111111111111111
    

    or from __future__ import division, which the forces / to adopt Python 3.x's behavior that always returns a float.

    >>> from __future__ import division
    >>> (10 - 20) / (100 - 10)
    -0.1111111111111111
    
    0 讨论(0)
  • 2020-11-21 06:47

    In python cv2 not updated the division calculation. so, you must include from __future__ import division in first line of the program.

    0 讨论(0)
  • 2020-11-21 06:48

    You need to change it to a float BEFORE you do the division. That is:

    float(20 - 10) / (100 - 10)
    
    0 讨论(0)
  • 2020-11-21 06:53

    Either way, it's integer division. 10/90 = 0. In the second case, you're merely casting 0 to a float.

    Try casting one of the operands of "/" to be a float:

    float(20-10) / (100-10)
    
    0 讨论(0)
  • 2020-11-21 06:56

    Specifying a float by placing a '.' after the number will also cause it to default to float.

    >>> 1 / 2
    0
    
    >>> 1. / 2.
    0.5
    
    0 讨论(0)
  • 2020-11-21 07:00

    Make at least one of them float, then it will be float division, not integer:

    >>> (20.0-10) / (100-10)
    0.1111111111111111
    

    Casting the result to float is too late.

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