Functional looping in R

r

#1

I am attempting this simple problem of solving f(x)=x^2 - 2*x - 2 = 0 by using Newton Raphson method and hence counting the number of iterations(it) required. {using looping by function recurssion}

it<-1
NR <- function(x) {
 f <- x^2-2*x-2
 fd<- 2*x-2
 x1<- x -f/fd
 f1 <- x1^2-2*x1-2
 if(abs(f1)>=0.0001){
 it<- it+1
 NR(x1)
 }
else{
print("The solution by NR method is :")
print(x1)
print("The number of iterations are :")
print(it)
 }
}
NR(3)

I am getting the correct solution for x but the iteration is not incrementing even though it is declared as global.Please share if any conceptual mistake I am doing in using the object declaration.


#2

Hi @Abhay01,

There is a small error in the code. Basically, when you iterate the value of ‘it’ in the function NR, it generates a local variable ‘it’ and iterates it instead. To iterate the global variable use the following code :

it<<- it+1

This will iterate the global variable. Rest of the logic is fine. It will give you the correct result.

Regards,
Shashwat


#3

Hi @shashwat.2014,

Thankyou for correction.It works.

Though one would expect R to give warning or error of “object not found” in such cases.

Regards.


#4

R will not generate an error in this instance because in the first iteration, the within function value of it is set to the value from the parent environment + 1. Therefore, no error is generated. Once the local value is instantiated, it is used for subsequent iterations of the loop. This is consistent with R’s pattern for resolving object names: start with the child environment, then move up the environment chain until the global environment is reached.

> it <- 1
> 
> testFunction <- function() {
+      for (i in 1:5) {
+           it <- it + 1
+           message(paste("value of it is:",it))
+      }
+ }
> testFunction()
 value of it is: 2
 value of it is: 3
 value of it is: 4
 value of it is: 5
 value of it is: 6
> it
[1] 1
> 

regards,

Len


#5

Thankyou. :slight_smile: nicely explained.