属于我写的《Matlab材料科学与基础——作出特定晶面指数在简单体心立方中所表示的面》的副产品。。。点击打开链接
纯小数和纯整数的情况都比较好做,并且两者可以互相转化
我讨论一下小数和整数混合的。
主要思路是先读出小数位数,再扩大相应倍数变成整数问题。对于整数问题,首先求最小公倍数,然后相除就行了。
数据:
(本来打算用13, 25.76, 31.34,但得到警告,并且结果已经到了10的15次方这个数量级。。。。所以说,还是用小的来测试吧。算法本身没问题,但是数据太大的话,计算量应该是指数级增长。。。。)
3,5.7,1.3
代码:
clc
clear all
close all
a=[3,5.7,1.3];
%a=[4,2,6];
for i=1:3
digitNum(i)=calDigit(a(i));
end
maxD=max(digitNum);
a=a.*(10^maxD);
num=lcm(a(1),lcm(a(2),a(3)));
disp(['The greatest common divisor is: ',num2str(num),' The ratio']);
a=num.*a;
num=gcd(a(1),gcd(a(2),a(3)));
a=a./num;
a
function digitNum=calDigit(a0)
a=mod(a0,1);%the fraction part
div=0.1;
digitNum=0;
while abs(a-0)>1e-12
a=mod(a,div);
digitNum=digitNum+1;
div=10^(-digitNum-1);
end
disp(['The number of digits is: ',num2str(digitNum)]);
结果:
The number of digits is: 0
The number of digits is: 1
The number of digits is: 1
The greatest common divisor is: 7410 The ratio
a =
30 57 13
gcd求最大公约数,lcm求最小公倍数