Matlab dec2bin给出了错误的值 [英] Matlab dec2bin gives wrong values

查看:196
本文介绍了Matlab dec2bin给出了错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Matlab的dec2bin将十进制数转换为二进制字符串.但是,我得到了错误的结果.例如:

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

我在C ++实现和Wolfram alpha中都进行了检查,正确的结果是:

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

1011100100011110100101001111010011000111111100011011001001010111

我对Matlab的desc2bin的使用有问题吗?

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

谢谢

吉尔.

推荐答案

您的代码等效于:

x=13339262925365424727;
dec2bin(x)

但是,如果您检查x的值,您会发现它超出了双精度.该数字很大,要存储在64位double中.精度为2 ^ 11,请检查eps(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)

要处理大量数字,请使用符号工具箱中的vpa是个不错的选择吗?

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

这是使用vpa的解决方案:

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

用法:

>> ldec2bin(vpa('13339262925365424727'))

ans =

1011100100011110100101001111010011000111111100011011001001010111

/更新:

我遇到了dec2bin较短的符号变量实现:

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

这篇关于Matlab dec2bin给出了错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆