Why does Matlab's divisors function take so long when working on an ordinary integer?
2 ビュー (過去 30 日間)
Matlab takes 25 seconds to find the sets of divisors for 1000 integers. The user submitted function divisor() -- no s at the end, available in the File Exchange, can find the sets of divisors for 10,000 integers in less than one second. Why can't the built-in divisors function recognize that the parameter given to it is an integer within a range that can be handled in the expeditious manner, and do so?
回答 (1 件)
John D'Errico 2022 年 11 月 30 日
編集済み: John D'Errico 2022 年 11 月 30 日
You ALWAYS. ALWAYS. ALWAYS need to consider the arguments for a function. Does it work in double precision, or as a sym? Don't forget that compared to a double precision operation, a symbolic numerical call effectively makes a snail look blazingly fast. However, there are tradeoffs, as the symbolic tool is far more capable.
So divisors is a symbolic tool. It can handle a problem like this:
But as you see in the help, it also works on symbolic expressions that are not just numbers. Any code that works on double precision numbers will completely fail on that integer of course, as it is too large for a double.
SHOULD it have been written differently, and check the arguments, so if you pass in a double precision argument, it would work in double precision? Actually, it does look like divisors returns a double result, when you pass in a double as input.
But I'd bet that it uses the sym/factor tool to factor the input. And that code must be slower.
As a check, I wrote a tool a zillion years ago to compute the divisors of a number. It does work in double precision for the operation, IF the number can be factored as a double using double/factor.
1 2 3 4 6 8 9 12 16 18 24 36 48 72
(Note that it was written to return only the proper divisors of a number. So it does not return the number itself in that list.)
So my code is considerably faster.
But, is there a reason why you are asking us this question? We did not write it. So ask the author. But I might guess the target of this code was perceived to be mainly for factoring symbolic expressions, and the author decided the use of it to provide the factors of small integers specifically was not the main reason for being of that code.
But how do I know? How can anyone who is not the author know? Remember that code from TMW is code that should have passed through some sort of peer review there, from their own team on the symbolic toolbox, probably based on requirements from that team. The code was written as it was written. If you think it should operate differently, then submit a feature request to the MathWorks. Answers is not the correct vehicle for a feature request though.