要处理有理数而又不损失Matlab中的计算精度? [英] To handle rational number without losing accuracy of computation in Matlab?
问题描述
我想在计算中使用这个有理数而又不损失Matlab中图片的准确性:
I want to use this rational number in computations without losing the accuracy of the picture in Matlab:
f = 359.0 + 16241/16250.0
我认为例如f = uint64(359.0 + 16241/16250.0)
的存储会失去准确性,在Matlab中被视为360.
I think storing, for instance by f = uint64(359.0 + 16241/16250.0)
loses accuracy, seen as 360 in Matlab.
我认为处理事情的最好方法是永远不要存储价值,而要存储诸如此类的因素
I think the best way to handle the thing is never to store the value but to store its factors like
% f = a + b/c
a = 359
b = 16241
c = 16250
然后使用变量a,b和c进行计算,并将结果显示为图片.
and then doing computation by the variables a, b and c, and giving the result as a picture.
这是保持准确性的好方法吗?
推荐答案
如您所建议,如果您绝对不希望在存储有理数时失去准确性,那么最好的解决方案可能是按照数字的形式存储整数分量.
As you suggest, if you absolutely don't want to lose accuracy when storing a rational number, the best solution probably is to store the number in terms of its integer components.
除了将三个组成部分(f = a + b/c
)之外,还可以将表示减少为两个组成部分:f = n/d
.因此,每个有理数将被定义(并存储)为两个分量的整数矢量[n d]
.例如,示例中的数字f
对应于n=5849991
和d=16250
.
Instead of your three components (f = a + b/c
) you can reduce the reprentation to two components: f = n/d
. Thus each rational number would be defined (and stored) as the two-component integer vector [n d]
. For example, the number f
in your example corresponds to n=5849991
and d=16250
.
为简化处理以这种方式存储的有理数的方法,可以定义一个辅助函数,该函数在应用所需的操作之前将从[n d]
表示形式转换为n/d
:
To simplify handling rational numbers stored this way, you could define a helper function which converts from the [n d]
representation to n/d
before applyling the desired operation:
useInteger = @(x, nd, fun) fun(x,double(nd(1))/double(nd(2)));
然后
>> x = sqrt(pi);
>> nd = int64([5849991 16250]);
>> useInteger(x, nd, @plus)
ans =
361.7719
>> useInteger(x, nd, @times)
ans =
638.0824
如果要在计算中实现任意高精度,则应考虑使用变量字符串参数的高精度算术(vpa
).使用这种方法,您可以指定所需的位数:
If you want to achieve arbitrarily high precision in computations, you should consider using variable-precision arithmetic (vpa
) with string arguments. With that approach you get to specify how many digits you want:
>> vpa('sqrt(pi)*5849991/16250', 50)
ans =
638.08240465923757600307902117159072301901656248436
这篇关于要处理有理数而又不损失Matlab中的计算精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!