uint64 equivalence

The program I'm writing needs to compare 64 bit integers. However, matlab doesn't seem to know when two numbers are equivalent.
For example:
>> 4467577170595717377 == 4467577170595717887
ans =
1
>> 4467577170595717377 == 4467577170595717888
ans =
0
Does anyone have any idea why it might be doing this? The numbers are well within the bounds of uint64 and any two numbers between the first two are considered equivalent.

Answers (1)

Hi,
you are comparing doubles (MATLAB's standard number format), not 64 bit integers.
x1=uint64(4467577170595717377)
x1 =
4467577170595717377
x2=uint64(4467577170595717887)
x2 =
4467577170595717887
x1==x2
ans =
0
Titus

5 Comments

Caution: in at least some versions, uint64(4467577170595717377) would operate by constructing the double precision number that most closely matches 4467577170595717377, and then converting that to uint64.
For example in 2008b,
>> uint64(4467577170595717887)
ans =
4467577170595717632
Even sscanf() of the number might not work:
>> sscanf('4467577170595717887','%lu')
ans =
4.46757717059572e+18
I was thinking you could use dec2bin, lop off the end bits and convert back using bin2dec but it has a limit of 52bits. You could probably write your own version that converts back directly to uint64.
and probably write a uint64str2bin as well since you want to avoid all conversion to double.
Jan
Jan on 20 Jun 2011
@Walter: Thanks for mentioning this strange feature. The UINT64 support of Matlab has not been satisfactory for a long time.
Steve Eddins
Steve Eddins on 20 Jun 2011
@Jan, @Walter: The behavior Walter mentioned was fixed in R2010b. Then in R2011a, a core set of arithmetic and other functions was modified to work natively with uint64 and int64, including plus (+), minus (–), uminus (–), times (.*), rdivide (./), ldivide (.\), power (.^), rem, mod, bitcmp, any, all, sum, diff, colon (:), sign, accumarray, and bsxfun.

Sign in to comment.

Asked:

on 20 Jun 2011

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!