フィルターのクリア

How to get the Least common multiple of a fractional number

21 ビュー (過去 30 日間)
Tristan
Tristan 2013 年 11 月 13 日
回答済み: Martin Grden 2024 年 3 月 1 日
for example:
>> lcm(8,20)
ans =
40
works
>> lcm(1.6,1)
doesn't work :(

回答 (4 件)

Walter Roberson
Walter Roberson 2013 年 11 月 13 日
rat(1/1.6)
and take the denominator term.

Kaixiang Wang
Kaixiang Wang 2015 年 8 月 23 日
Inspired by one of the comments, actually you could do this with Symbolic toolbox.
x=sym(1.6);
y=sym(1);
lcm(x,y) % should give you the answer you want
  2 件のコメント
Xiangming Hao
Xiangming Hao 2017 年 5 月 17 日
It works, thank you!
Walter Roberson
Walter Roberson 2017 年 5 月 17 日
Yes, sym() of a double precision value by default tries to represent the value as a rational value, looking for a good approximation -- for example it is able to figure out pi/2 as a multiple of sym('pi') . And once you have rational form then you can proceed towards lcm()

サインインしてコメントする。


John D'Errico
John D'Errico 2013 年 11 月 13 日
編集済み: John D'Errico 2013 年 11 月 13 日
Actually, no, you cannot get that result.
The real problem is that MATLAB does not actually represent 1.6 as 1.6. Using my HPF tool, we find that 1.6 is actually stored as
hpf(1.6,60)
ans =
1.60000000000000008881784197001252323389053344726562500000000
Yep. Not exactly 1.6. Floating point storage in a binary form prevents storing most decimal numbers exactly.
In turn, this means that any algorithm that yields a LCM that works on integers will fail when looking for exact multiples of real numbers.

Martin Grden
Martin Grden 2024 年 3 月 1 日
A solution for more than two numbers. You need to split the fractions into two input vectors.
function result=lcm_e(numeratorVector,denominatorVector)
% horiz. vector args req.
z=denominatorVector;
if length(z)==2
lcmDenominatorVector=lcm(z(1),z(2));
else
lcmDenominatorVector=lcm(z(1), ilcm_e(z(2:end)));
end
z=(lcmDenominatorVector./denominatorVector).*numeratorVector;
if length(z)==2
lcmNumeratorVector=lcm(z(1),z(2));
else
lcmNumeratorVector=lcm(z(1), ilcm_e(z(2:end)));
end
result=lcmNumeratorVector/gcd(lcmNumeratorVector,lcmDenominatorVector);
function ierg=ilcm_e(z)
if length(z)==2
ierg=lcm(z(1),z(2));
else
ierg=lcm(z(1),ilcm_e(z(2:end)));
end
end
end

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by