Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- f <- function(x){
- return ( (x[1] -3)^2 + (x[2]-1)^2 )
- }
- grad_f <- function(x) {
- return ( c(2*(x[1]-3), 2*(x[2]-1) ) )
- }
- descent_gradient <- function(f, gradf, x, sigma, precision) {
- while (abs(f(x)) > precision){
- x <- x + sigma * -gradf(x)
- }
- return (x)
- }
- g <- function(x){
- return (-x^3 + x^2 -2*x +5)
- }
- dg <- function(x){
- return (-3*x^2 +2*x -2)
- }
- newton <- function (g, dg, x, precision){
- while(abs(g(x)) > precision){
- x <- x - g(x)/dg(x)
- }
- return (x)
- }
- h <- function(x){
- return (10*x^4 -20*x^3 -90*x^2 +20*x +80)
- }
- dh <- function(x){
- return (40*x^3 -60*x^2 -180*x +20)
- }
- ddh <- function(x){
- return (120*x^2 -120*x -180)
- }
- main <- function(){
- x <- c(4,5)
- #cat(f(x), "\n")
- #cat(grad_f(x), "\n")
- xm <- descent_gradient(f, grad_f, x, sigma = 0.1, precision = 10^-6)
- cat(xm, " ", f(xm), "\n")
- xn <- newton(g, dg, 5, precision = 10^-6)
- cat(xn, " " , g(xn), "\n")
- xm <- newton(dh, ddh, 2, precision = 10^-6)
- cat(xm, " " , dh(xm), " ", h(xm) ,"\n")
- x <- seq(2.5,3.5, by = 0.01)
- plot(x, h(x), type ="l")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement