How to Implement Newton's Method in R?

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 3K views
spamiam
Messages
360
Reaction score
1
Hello,

I've been trying to write a program in R that implements Newton's method. I've been mostly successful, but there are two little snags that have been bothering me. Here's my code:

Code:
Newton<-function(f,f.,guess){
	#f<-readline(prompt="Function? ")
	#f.<-readline(prompt="Derivative? ")
	#guess<-as.numeric(readline(prompt="Guess? "))
	a<-rep(NA, length=1000)
	a[1]<-guess
	a[2]<-a[1]-f(a[1])/f.(a[1])
	for(i in 2:length(a)){
		if(a[i]==a[i-1]){break
		}else{
		a[i+1]<-a[i]-f(a[i])/f.(a[i])
		}
	}	
a<-a[complete.cases(a)]
return(a)
}

1) I can't get R to recognize the functions f and f. if I try using readline() to prompt for user input. I get the error "Error in Newton() : could not find function "f."" However, if I comment out the readlines (as above), define f and f. beforehand, and then everything works fine.

2) I've been trying to make R calculate the derivative of a function. The problem is that the class object with which R can take symbolic derivatives is expression(), but I want to take the derivative of a function() and have it give me a function(). In short, I'm having trouble with type conversion between expression() and function(). I have an ugly but effective solution for going from function() to expression(). Given a function f, D(body(f)[[2]],"x") will give the derivative of f. However, this output is an expression(), and I haven't been able to turn it back into a function(). Do I need to use eval() or something? I've tried subsetting, but to no avail. For instance:

Code:
> g<-expression(sin(x))
> g[[1]]
sin(x)
> f<-function(x){g[[1]]}
> f(0)
sin(x)

when what I want is f(0) = 0 since sin(0) = 0.
 
on Phys.org
Bump? Anyone here know R?
 
In case anyone was curious, the answers to my questions can be found here: http://stackoverflow.com/questions/8857042/r-type-conversion-expression-function.

Here's my revised code:

Code:
Newton<-function(f,f.,guess){
    g<-readline(prompt="Function? ")
    g<-parse(text=g)
    g.<-D(g,"x")
    f<-function(x){eval(g[[1]])}
    f.<-function(x){eval(g.)}
    guess<-as.numeric(readline(prompt="Guess? "))
    a<-rep(NA, length=1000)
    a[1]<-guess
    a[2]<-a[1]-f(a[1])/f.(a[1])
    for(i in 2:length(a)){
        if(a[i]==a[i-1]){break
        }else{
        a[i+1]<-a[i]-f(a[i])/f.(a[i])
        }
    }   
a<-a[complete.cases(a)]
#a<-a[1:(length(a)-1)]
return(a)
}