所以我有以下函数,它使用牛顿-拉夫森方法找到函数的根。我认为我的问题是相对简单的:我希望函数找到平方根给定的正数,使用牛顿拉斐尔方法。帮助吗?
# FUNCTION:
newton <- function(f, delta = 0.0000001, x_0 = 2, n=1000){
h = 0.0000001
i = 1; x1 = x_0
p = numeric(n)
while (i <= n) { #while i is less than or equal to n(1000), continue iterations
df.dx = (f(x_0 + h) - f(x_0)) / h #
x1 = (x_0 - (f(x_0) / df.dx)) # output of original guess minus (f(x)/f´(x)) (formula for root finding)
p[i] = x1 # counts iteration so we don't exceed 1000
i = i+1 # same as ^
if (abs(x1 - x_0) < delta) break # if output is less than delta: end iteration. Otherwise continue. (x1-x_0=if new value is below our threshold, stop)
x_0 = x1
}
return(p[1: (i-1)]) #
}
############## TEST ###############
func1 <- function(x){
x^5 - 7
}
newton(func1)
#VARIABLES are
#f = the function we input
#delta = the accuracy threashold we are willing to accept
#x_0 = our initial guess
#n = the number of iterations
#h = the distance from X1 to X0,this value much little ,the root much #closed.
#abs is a sys
一个可能的解决方案:
newton <- function(f, delta = 0.0000001, x_0 = 2, n=1000){
h = 0.0000001
i = 1; x1 = x_0
p = numeric(n)
while (i <= n) { #while i is less than or equal to n(1000), continue iterations
df.dx = (f(x_0 + h) - f(x_0)) / h #
x1 = (x_0 - (f(x_0) / df.dx)) # output of original guess minus (f(x)/f´(x)) (formula for root finding)
p[i] = x1 # counts iteration so we don't exceed 1000
i = i+1 # same as ^
if (abs(x1 - x_0) < delta) break # if output is less than delta: end iteration. Otherwise continue. (x1-x_0=if new value is below our threshold, stop)
x_0 = x1
}
return(list(result = x1, iterations = p[1:i-1]))
}
nthrootsub <- function(input, nth, x){ x^nth - input}
nthroot <- function(input, nth) {newton(function(x) nthrootsub(input, nth, x))}
############## TEST ###############
10^(1/5)
#[1] 1.584893
nthroot(10,5)
#$result
#[1] 1.584893
#$iterations
#[1] 1.725000 1.605878 1.585435 1.584894 1.584893 1.584893