Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab dec2bin gives wrong values

Tags:

matlab

I'm using Matlab's dec2bin to convert decimal number to binary string. However, I'm getting wrong results. For example:

>> dec2bin(13339262925365424727)

ans =

1011100100011110100101001111010011000111111100011011000000000000

I checked both in a C++ implementation and in wolfram alpha and the correct result is:

1011100100011110100101001111010011000111111100011011001001010111

Is there any problem with my usage of Matlab's desc2bin?

Thanks,

Gil.

like image 395
GilLevi Avatar asked Jan 30 '26 08:01

GilLevi


2 Answers

Your code is equivalent to:

x=13339262925365424727;
dec2bin(x)

but if you check the value of x, you will notice that it outruns double precision. The number is simply to large to be stored in a 64bit double. The precision is 2^11, check eps(x)

To deal with large numbers, using vpa from the symbolic toolbox is a good option, is this available?

Here is a solution using vpa:

function l=ldec2bin(x)
if x>2^52
    head=floor(x/2^52);
    tail=x-head*2^52;
    l=[ldec2bin(head),dec2bin(double(tail),52)];
else
    l=dec2bin(double(x));
end
end

usage:

>> ldec2bin(vpa('13339262925365424727'))

ans =

1011100100011110100101001111010011000111111100011011001001010111

/Update:

I came across a much shorter implementation of dec2bin for symbolic variables:

>> sdec2bin=@(x)(feval(symengine,'int2text',x,2))

sdec2bin = 

    @(x)(feval(symengine,'int2text',x,2))

>> sdec2bin(sym('13339262925365424727'))

ans =

1011100100011110100101001111010011000111111100011011001001010111
like image 77
Daniel Avatar answered Feb 01 '26 20:02

Daniel


The integer seems to long, maybe you should try de2bi function; http://www.mathworks.com/help/comm/ref/de2bi.html

like image 41
AykutE Avatar answered Feb 01 '26 20:02

AykutE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!