Читать книгу Applied Numerical Methods Using MATLAB - Won Y. Yang - Страница 37

1.3.3 Iterative Routine vs. Recursive Routine

Оглавление

In this section, we compare an iterative routine and a recursive routine performing the same job. Consider the following two functions ‘ fctrl1(n)/fctrl2(n)’, whose common objectives is to get the factorial of a given nonnegative integer k.

(1.3. 5)

They differ in their structure. While ‘ fctrl1()’ uses a for loop structure, ‘ fctrl2()’ uses the recursive (self‐calling) structure that a program uses itself as a subroutine to perform a sub‐job. Compared with ‘ fctrl1()’, ‘ fctrl2()’ is easier to program as well as to read, but is subject to runtime error that is caused by the excessive use of stack memory as the number of recursive calls increases with large n. Another disadvantage of ‘ fctrl2()’ is that it is time‐inefficient for the number of function calls, which increases with the input argument ( n). In this case, a professional programmer would consider the standpoint of users to determine the programming style. Some algorithms like the adaptive integration (Section 5.8), however, may fit the recursive structure perfectly.

function m=<b>fctrl1</b><![CDATA[(n) m=1; for k=2:n, m=m*k; end function m=<b>fctrl2</b><![CDATA[(n) if n<=1, m=1; else m=n*fctrl2(n-1); end

Applied Numerical Methods Using MATLAB

Подняться наверх