フィルターのクリア

Calculating power in a loop has different result from the matlab power function

2 ビュー (過去 30 日間)
kuku hello
kuku hello 2022 年 3 月 21 日
コメント済み: kuku hello 2022 年 3 月 21 日
Hello, I tried to calculate 13^(15) using a for loop, and using the power function of matlab and I get different results.
Can someone explain to me how come? For example:
num = 13;
pow = 15;
for i = 2:pow
num = num*13;
end
result = 13^15;
num - result % The result here is 8, which means the difference between the two numbers is 8?
ans = 8
result ~= num % It comes out to be true
ans = logical
1

採用された回答

Jan
Jan 2022 年 3 月 21 日
編集済み: Jan 2022 年 3 月 21 日
Neither the power operator nor the loop produce the exact result:
x = sym(13);
x^15
ans = 
51185893014090757
fprintf('%.0f\n', 13^15)
51185893014090752
y = 13;
for k = 2:15, y = y * 13; end
fprintf('%.0f\n', y)
51185893014090760
This effect is expected, because the value is larger than the maximum value, which has an exact representation in the IEEE754 format. This format is used in Matlab, other numerical software and in modern CPUs. It uses 52 bits for the mantissa. Then numbers, which need a 53'th bit or more cannot be store accurately anymore.
This happens in the 15th iteration of the loop, when the value exceeds 2^53, which is about 9e15. See: doc flintmax

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by