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 m
This first problem arises because readline
reads in a text string, whereas what you need is an expression. You can use parse()
to convert the text string to an expression:
f <-readline(prompt="Function? ")
sin(x)
f
# [1] "sin(x)"
f <- parse(text = f)
f
# expression(sin(x))
g <- D(f, "x")
g
# cos(x)
To pass in values for the arguments in the function call in the expression (whew!), you can eval()
it in an environment containing the supplied values. Nicely, R will allow you to supply those values in a list supplied to the envir=
argument of eval()
:
> eval(f, envir=list(x=0))
# [1] 0