简体   繁体   中英

python: error comparing numbers

I'm working on a college project, it's about simulating a regular Markov chain, so I have to confirm that each the vector/row of the matrix sum 1.

Here is the code:

nRC means number of columns/rows in this case nRC is equal 3

def checkingVector(vectorM):
    y = 0
    for x in range(0,nRC):
        for z in range(0,nRC):
            y += vectorM[x][z]
            print y
        if y != 1.0:
            print y
            return false
        else :
            y = 0
    return true

validMatrix = checkingVector(m)
if validMatrix == false:
    print "Invalid Matrix"
    print m
else:
    equationA = []
    for x in range(0,nRC):
        equationA.append(1)
    equationA.append(0)
    print equationA
    print m

And this works well, but it fails with this matrix

(0.6 0.3 0.1)
(0.2 0.5 0.3)
(0.1 0.2 0.7)

So each row of this matrix is equal to 1 and when I apply my function to this matrix it returns invalid matrix.

I have printed the y variable to make sure it contains 1 and it does but the program still goes to the consecuence of the function if.

What am I doing wrong and how can I address it?

You're a victim of Floating Point Arithmetic: Issues and Limitations

In [1]: 0.6 + 0.3 + 0.1
Out[1]: 0.9999999999999999

Floating point numbers are not precise. Therefore, never test for equality but rather something like

if abs(y-1) <= 0.0000001:
    # close enough

Or use the decimal module .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM