Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23247

Recursive R function and its Python translation behave differently

$
0
0

Here is a recursive R function involving a matrix S from the parent environment:

f <- function(m, k, n) {  if(n == 0) {    return(100)  }  if(m == 1) {    return(0)  }  if(!is.na(S[m, n])) {    return(S[m, n])  }  s <- f(m-1, 1, n)  i <- k  while(i <= 5) {    if(n > 2) {      s <- s + f(m, i, n-1)    } else {      s <- s + f(m-1, 1, n-1)    }    i <- i + 1  }  if(k == 1) {    S[m, n] <- s  }  return(s)}

Here is the result of a call to this function:

> n <- 4> S <- matrix(NA_real_, nrow = n, ncol = n)> f(n, 1, n)[1] 127500

Now, here is the Python version:

import numpy as npdef f(m, k, n):  if n == 0:    return 100  if m == 1:    return 0  if S[m-1, n-1] is not None:     return S[m-1, n-1]  s = f(m-1, 1, n)  i = k  while i <= 5:    if n > 2:      s = s + f(m, i, n-1)    else:      s = s + f(m-1, 1, n-1)    i = i + 1  if k == 1:    S[m-1, n-1] = s  return s

The call:

>>> n = 4>>> S = np.full((n, n), None)>>> f(n, 1, n)312500

The Python result is different from the R result. Why?

One gets identical results if one replaces

  if S[m-1, n-1] is not None:     return S[m-1, n-1]

with

  if k == 1 and S[m-1, n-1] is not None:     return S[m-1, n-1]

I also have a C++ version of this function, and it has the same behavior as the R function.


Viewing all articles
Browse latest Browse all 23247

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>