MATLAB计算小数数组的最小公倍数和最大公因数

目录

1. 基本思想

2. DEMO

 3. 计算最小公倍数(LCD)

 4. 计算最大公因数(GCM)

1. 基本思想

把数组乘以数次10,直到变成整数数组为止;遍历整数数组的元素,用matlab自带的lcm和gcd函数;求出整数数组的最小公倍数和最大公因数之后再除以相应次数的10

(其实很简单,就是不知道为啥网上没找到相应的函数,就自己速度弄了一个;写得很急,如果发现有中间有什么问题请联系我!)

2. DEMO

array = [0.1, 0.02, 3, 0.25];
lcm = LCM(array);
gcd = GCD(array);

disp(['LCM: ', num2str(lcm)])
disp(['GCD: ', num2str(gcd)]);

运行结果: 

《MATLAB计算小数数组的最小公倍数和最大公因数》

 3. 计算最小公倍数(LCD)

function result = LCM(array)
n = length(array);
tmp = array;
exp = 0; % Record how many times the array has been multiplied by 10
while ~is_intarray(tmp) % Whether array multiplied by 10's has become integer
    tmp = tmp * 10;
    exp = exp + 1;
end
result = lcm_array(uint32(tmp),n); % Calculate the LCM of the integer array which has been multiplied by 10's
if (exp > 0) % If the array is multiplied by 10's, divide the LCM by 10's in return
    result = double(result) / 10^exp;
end
end

 % Calculate the LCM of an integer array
function result = lcm_array(array, n)
result = array(1);
for i = 1:n-1
    result = lcm(result,array(i+1)); 
end
end

这里面用到一个判定被乘了10的数组是否已经变成整数了:

function result = is_intarray(array)
tmp = round(array);
if (abs(array - tmp) < 10^(-10))
    result = 1;
else
    result = 0;
end
end

 4. 计算最大公因数(GCM)

function result = GCD(array)
n = length(array);
tmp = array;
exp = 0; % Record how many times the array has been multiplied by 10
while ~is_intarray(tmp) % Whether array multiplied by 10's has become integer
    tmp = tmp * 10;
    exp = exp + 1;
end
result = gcd_array(uint32(tmp),n); % Calculate the LCM of the integer array which has been multiplied by 10's
if (exp > 0) % If the array is multiplied by 10's, divide the LCM by 10's in return
    result = double(result) / 10^exp;
end
end

% Calculate the GCD of an integer array
function result = gcd_array(array, n)
result = array(1);
for i = 1:n-1
    result = gcd(result,array(i+1)); 
end
end

    原文作者:undaria
    原文地址: https://blog.csdn.net/undaria/article/details/120626078
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞