cycle for calculation of a function

Asked

Viewed 144 times

3

I intend to cycle for but it’s not working. My R knowledge is still poor. I intend to calculate a function F(y, x) = 1 + y + y^2 + ... + y^x = sum(y^(0:x)).

I wrote the following code, but it is giving a result that is not what I want. What error?

> sum <- 1 
> for(i in 0:3){
+     for(y in 0:3){
+             sum <- sum + y ^ (i)
+     }
+ }

print( sum ) [1] 61

    1. Choose another name for the variable sum, is already a function of R; 1) Start with sum <- 0; 2) Take the cycle from the inside, there is doing nothing there.
  • Note to comment above: If you want you can start with sum <- 1 but then the cycle for will be for values 1:x and not 0:x.

2 answers

2

Your code is doing exactly what you specified. You provided a value of x and a value of y, and that was the result returned:

> 0^0+0
[1] 1

To use for, you must specify a sequence, for example:

x <- 3

> for(i in x) print(i+1)
[1] 4

> for(i in 1:x) print(i+1)
[1] 2
[1] 3
[1] 4

To store the values, you must have an object of appropriate size to receive the result of each turn, or you will only have the last value:

for(i in 0:x) y = x ^ i + x
> y 
[1] 30
# o objeto y teve o valor atualizado a cada volta

y <- rep(NA, x+1)
for(i in 0:x) y[i+1] = x ^ i + x
> y
[1]  4  6 12 30

But R is optimized for vector operations, it is best to avoid loops whenever possible. You already came to the solution when you edited your question, just didn’t realize it was just that:

suaFuncao <- function(y, x) sum(y^(0:x))

> suaFuncao(2, 3)
[1] 15
  • Effectively your solution that avoids loops is the best solution. However for this particular case I have to use the 'for' cycle. As for the 'for' cycle I did the following but I get an error. '> n <-0:4 > y <-0:4 > for(i in 0:x) y = 1 + y 2 + y x Warning message: In 0:n : numerical Expression has 5 Elements: only the first used'

  • Basically intended exactly what it has in the 'yourFuncao' where the user puts the value of X and the value of Y and returns the value of the function but with cycle 'for'

  • You already arrived at the code, it’s just that you didn’t realize that it is śo not to use a loop. I edited the answer stating this.

  • Its function @Carlos is a simple and clear solution for me, I got to understand a little more of the matter. But for the specific case the formator asked for a cycle for . I edited my topic with something else I did, but the result is not correct. In this case the result should be 40 and not 61 . Can help?

1

Here is a cycle for very simple. And the comparison with the result of the answer from Carlos Eduardo Lagosta.

suaFuncao <- function(y, x) sum(y^(0:x))

suaFuncao2 <- function(y, x){
  s <- 1
  for(k in seq_len(x)) s <- s + y^k
  s
}

suaFuncao(2, 3)
#[1] 15

suaFuncao2(2, 3)
#[1] 15

Browser other questions tagged

You are not signed in. Login or sign up in order to post.