简体   繁体   中英

Python interpreting equal values as non-equal

For this part of the code, which is inside a for loop

s = 'cl_num = %d, prev_cl_num = %d\n' % (cl_num, prev_cl_num);
fd.write( s );
if cl_num != prev_cl_num:
    bb.instructions[i].is_cache_miss = 1;
    s = 'instruction %x is cache miss, cl_num = %d, prev_cl_num = %d, base_cache_line = %d\n' % (bb.instructions[i].address, cl_num, prev_cl_num, base_cache_line);
    fd.write( s );
    bb.instructions[i].cache_line = cl_num - base_cache_line;
    prev_cl_num = cl_num;

I get an output, as this in the fd file,

cl_num = 65557, prev_cl_num = 65557
instruction 400558 is cache miss, cl_num = 65557, prev_cl_num = 65557, base_cache_line = 65557
cl_num = 65557, prev_cl_num = 65557
instruction 400560 is cache miss, cl_num = 65557, prev_cl_num = 65557, base_cache_line = 65557
cl_num = 65557, prev_cl_num = 65557
instruction 400568 is cache miss, cl_num = 65557, prev_cl_num = 65557, base_cache_line = 65557
cl_num = 65557, prev_cl_num = 65557
instruction 400570 is cache miss, cl_num = 65557, prev_cl_num = 65557, base_cache_line = 65557

You see, the condition cl_num != prev_cl_num gets evaluated to true even when cl_num is equal to prev_cl_num . Why so?

You have floating point values, but only write the integer portion to your file:

>>> '%d' % 3.3
'3'

Note how the .3 decimal portion has been ignored; %d calls int() on the interpolated value.

When writing debugging values, always use repr() , or %r in formatting:

s = 'cl_num = %r, prev_cl_num = %r\n' % (cl_num, prev_cl_num);

repr() on float values formats them as if using a %17g formatter; 17 decimals are shown, scientific notation is used when the exponent is 17 or up.

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