필터 지우기
필터 지우기

why square takes longer than multiplication

조회 수: 6 (최근 30일)
Jerry
Jerry 2011년 12월 6일
My question is why in matlab square takes more time than multiplication. I read an article, say, square actually can be done a little bit quicker than multiplication. But the test code below doesn't support this. So how does Matlab implement square(and other integer power, which I'm also interested in)? The test code is following:
a=1; tic; for k=1:10000 b=a*a; end toc;
Then, without any changes except "b=a*a" is changed into "b=a^2":
a=1; tic; for k=1:10000 b=a^2; end toc;
Consequently, multiplication takes about 77 microseconds while square takes 500+.
Thanks in advance!! Jerry

채택된 답변

Walter Roberson
Walter Roberson 2011년 12월 6일
The .^ operator is implemented in terms of pow(), which can involve logs. .^ does not appear to optimize .^2
If I recall correctly, there is a File Exchange contribution that decomposes integer powers to create the optimal multiplication series.
  댓글 수: 3
Jerry
Jerry 2011년 12월 6일
Thank you very much. Do you know if there is anyway to find how Matlab writes its built-in function?
Walter Roberson
Walter Roberson 2011년 12월 6일
The way to find the code for a built-in MATLAB function is to get a code development job with MathWorks.
I did at one time write code (for my work) that decomposed integer powers into multiplications. Eventually, though, I removed that code again, as I was able to show that the result was lower precision than .^ was able to get.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2011년 12월 6일
Squaring is cheaper than the multiplication if it is performed in C and if it is implemented using the multiplication (!):
double a = 3.14159265, b;
b = a * a; // Standard
a *= a; // Slightly faster inplace squaring
  댓글 수: 1
Jerry
Jerry 2011년 12월 6일
Thank you! I hope to accept your answer as well, but unexpectedly I can accept just one.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by