将十进制数转换为向量 [英] Convert decimal number to vector

查看:108
本文介绍了将十进制数转换为向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在matlab中,我想将其转换为

In matlab I want to convert this:

12345.6788993442355456789

转换为向量

[1 2 3 4 5 6 7 8 8 9 9 3 4 4 2 3 5 5 4 5 6 7 8 9]

我发现了几种使用scanf, num2str,...之类的命令将整数转换为向量的解决方案,但这些解决方案不适用于非整数,并且有些解决方案存在数字小数位数很大的问题...

I have found several solutions to convert a integer into a vector using commands like scanf, num2str,... but those don't fit with non-integers, and some solutions have problems with numbers with a large number of decimal places...

需要这种转换,因为我想查看并使用数字的所有数字.

That kind of conversion is needed because I want to see and use all of the digits of the number.

推荐答案

您从哪些输入源获得这些数字?所有这些数字都有意义吗?您的示例数字已经超出了double数值类型的相对精度. eps函数将告诉您要获取的舍入值.

What input source are you getting those numbers from? And are all those digits significant? Your example numbers are already beyond the relative precision of the double numeric type. The eps function will tell you how much roundoff you're getting.

>> sprintf('%.20f', 12345.6788993442355456789)
ans =
12345.67889934423500000000
>> eps(12345.6788993442355456789)
ans =
    1.818989403545857e-012
>> sprintf('%.20f', 23432.23432345678911111111111100998)
ans =
23432.23432345678900000000
>> eps(23432.23432345678911111111111100998)
ans =
    3.637978807091713e-012

在Matlab源代码中键入数字时,会将其视为类型为double的文字.输入这些数字后,许多数字都会立即丢失.请参阅此问题以获取更多讨论:在MATLAB中,变量确实是默认情况下是双精度?.

When you type a number in to Matlab source code, it's treated as a literal of type double. So many of those digits are lost as soon as you enter them. See this question for more discussion: In MATLAB, are variables REALLY double-precision by default?.

如果您确实要保留所有这些数字,则首先需要避免将它们存储为双精度.从字符串中的完整数字开始,然后对其进行解析.

If you really want to preserve all those digits, you need to avoid storing them in doubles in the first place. Start off with the full number in a string, and then parse it.

function out = parseLongDecimal(str)
ixDot = find(str == '.');
if isempty(ixDot)
    out.whole = arrayfun(@str2double, str);
    out.fraction = [];
else
    out.whole = arrayfun(@str2double, str(1:ixDot-1));
    out.fraction = arrayfun(@str2double, str(ixDot+1:end));
end

这将保留所有数字.

>> xAsStr = '23432.23432345678911111111111100998';  % as a string literal, not numeric
>> parseLongDecimal(xAsStr)
ans = 
       whole: [2 3 4 3 2]
    fraction: [2 3 4 3 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 1 1 1 0 0 9 9 8]

根据您的用例,您也可以将其放入Java BigDecimal对象中并在其中使用.

Depending on your use case, you could also just throw it in a Java BigDecimal object and work with it there.

>> jx = java.math.BigDecimal(xAsStr)
jx =
23432.23432345678911111111111100998

这篇关于将十进制数转换为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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