类型INT32变量的平方根



我尝试使用sqrt()函数来计算类型 int32 变量的平方根,但是我得到了此错误: for输入参数然后键入'int32'。,然后我发现有一个称为 isqrt()的函数,该函数计算了类型整数变量的平方根,但在我的MATLAB版本(R2013A)中不存在。我尝试下载此功能,但找不到。我尝试将价值驱动到(1/2),但整数只能提高到积极的积分力量。

所以有什么方法可以做到吗?

您可以使用匿名函数编写自己的isqrt

%// variable
A = int32(16)
%// helper function
isqrt = @(x) int32(sqrt(double(x)))
%// root
iroot = isqrt(A)

此功能应仅用作为此功能,如果您确定实际上可以计算根,因为将小数为int32(...)的小数值将围绕它,而不会显示错误。

为了使其更强大,您可以创建一个函数:

function iroot = isqrt(integer)
    root = sqrt(double(integer));
    if mod(root,1) == 0
        iroot = int32( root );
    else
        disp('Input has no integer root')
    end
end

这是一种解决方案,避免通过使用 fix从double转换为整数类型时发生舍入的解决方案,并且还通过使用castclass函数来支持任何整数类型:

isqrt = @(x) cast(fix(sqrt(double(x))), class(x));

所以:

>> isqrt(int32(15))
ans =
    3

但是

>> int32(sqrt(double(int32(15))))
ans =
           4

使用fix代替floor正确处理负值:

>> isqrt(int8(-15))
ans =
    0 +    3i

最新更新