Program not entering if statement

后端 未结 7 1830
走了就别回头了
走了就别回头了 2021-01-19 05:01

In my python program, an if statement is not being entered. I have simplified the code to the following:

x = -5
while x < 5:
    if (x == 0):
        prin         


        
相关标签:
7条回答
  • 2021-01-19 05:32

    To be precise to your query, floating point numbers are stored in computer hardware in binary(base 2) fractions. So even if you store some floating point like 0.01 in a variable, the computer would ultimately convert that into it's equivalent binary value. For your convenience, conversion of 0.01 float to binary:

    0.01 * 2 = 0.02 [0]
    0.02 * 2 = 0.04 [0] 
    0.04 * 2 = 0.08 [0]
    0.08 * 2 = 0.16 [0]
    0.16 * 2 = 0.32 [0]
    0.32 * 2 = 0.64 [0]
    0.64 * 2 = 1.28 [0]
    0.28 * 2 = 0.56 [0]
    0.56 * 2 = 1.12 [1]
    ...
    

    This calculation would be too lengthy to show here in full and probably won't end at all. But the fact i want to state here is that, most fractional decimals cannot be exactly converted into binary fractions. As a result, the decimal point you store will be approximated by the binary floating fractions stored in the machine(which obviously can't store very very long binary value). So when the calculation is done with that value, you certainly shouldn't expect the accurate floating value. That's the case with putting x += 0.01 in your code. However conversion of 0.5 to it's binary equivalent would give:

    0.5 * 2 = 1.0 [1]
    

    So binary equivalent of 0.5 float is 0.1. Since it is perfectly represented in binary in your machine. You would get the exact result.

    It has nothing to do with your code or python. It's just the way computer hardware works :)

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