Hello , I am using Matlab 7.10.0(R2010a). I need to use mod function for int64 datatype. But it doesn't wok . Can you help me ?
2 次查看(过去 30 天)
显示 更早的评论
mod(ans(1),48) ??? Undefined function or method 'mod' for input arguments of type 'int64'
ans(1) is a first element of array ans of type int64.
0 个评论
回答(1 个)
Guillaume
2015-4-17
编辑:Guillaume
2015-4-17
Newer versions of matlab have mod implemented for int64, so maybe it is time to upgrade.
a = intmax('int64'); %for example
%use static method 'ValueOf' of bigInteger to convert int64 (long) into a BigInteger:
bi = javaMethod('valueOf', 'java.math.BigInteger', a)
%modulo operation needs another BigInteger
m = bi.mod(javaMethod('valueOf', 'java.math.BigInteger', 48));
%unfortunately matlab converts the long value return by the 'longValue' method into a double
%so the following may result in loss of precision
result = int64(m.longValue)
%to guarantee no precision loss, go throught the byte array representation:
barr = m.toByteArray;
[~, ~, endianness] = computer; %note that toByteArray always return bytes in big endian
if endianness == 'L' %so if machine is little endian
barr = flipud(barr); %flip the byte
end
if numel(barr) < 8 %toByteArray only return as many bytes as necessary
barr(8, 1) = 0; %so expand to the 8 required for int64
end
result = typecast(int8(barr), 'int64')
As per the comment above, the simplest way to get an int64 (long) value out of a BigInteger is through the longValue method. Unfortunately, matlab converts the long that it returns into a double, resulting in a loss of precision for large integers. The workaround is to get the byte representation and type cast the byte array back to int64.
Edit: Actually if you're on Windows, a much simpler way is to go through .Net, the Math.DivRem method:
System.Math.DivRem(intmax('int64'), 48)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!