Hello,(adsbygoogle = window.adsbygoogle || []).push({});

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:

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.Code (Text):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)

}

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:

when what I want is f(0) = 0 since sin(0) = 0.Code (Text):> g<-expression(sin(x))

> g[[1]]

sin(x)

> f<-function(x){g[[1]]}

> f(0)

sin(x)

**Physics Forums | Science Articles, Homework Help, Discussion**

Join Physics Forums Today!

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# R Type Conversion

Loading...

Similar Threads for Type Conversion |
---|

LaTeX How to type something in ##\LaTeX## in the title itself? |

**Physics Forums | Science Articles, Homework Help, Discussion**