Advertisement
Guest User

Untitled

a guest
Jan 17th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. f <- function(x){
  2. return ( (x[1] -3)^2 + (x[2]-1)^2 )
  3. }
  4.  
  5. grad_f <- function(x) {
  6. return ( c(2*(x[1]-3), 2*(x[2]-1) ) )
  7. }
  8.  
  9. descent_gradient <- function(f, gradf, x, sigma, precision) {
  10. while (abs(f(x)) > precision){
  11. x <- x + sigma * -gradf(x)
  12. }
  13. return (x)
  14. }
  15.  
  16. g <- function(x){
  17. return (-x^3 + x^2 -2*x +5)
  18. }
  19.  
  20. dg <- function(x){
  21. return (-3*x^2 +2*x -2)
  22. }
  23.  
  24. newton <- function (g, dg, x, precision){
  25. while(abs(g(x)) > precision){
  26. x <- x - g(x)/dg(x)
  27. }
  28. return (x)
  29. }
  30.  
  31.  
  32. h <- function(x){
  33. return (10*x^4 -20*x^3 -90*x^2 +20*x +80)
  34. }
  35.  
  36. dh <- function(x){
  37. return (40*x^3 -60*x^2 -180*x +20)
  38. }
  39.  
  40. ddh <- function(x){
  41. return (120*x^2 -120*x -180)
  42. }
  43.  
  44. main <- function(){
  45. x <- c(4,5)
  46. #cat(f(x), "\n")
  47. #cat(grad_f(x), "\n")
  48.  
  49. xm <- descent_gradient(f, grad_f, x, sigma = 0.1, precision = 10^-6)
  50. cat(xm, " ", f(xm), "\n")
  51.  
  52. xn <- newton(g, dg, 5, precision = 10^-6)
  53. cat(xn, " " , g(xn), "\n")
  54.  
  55. xm <- newton(dh, ddh, 2, precision = 10^-6)
  56. cat(xm, " " , dh(xm), " ", h(xm) ,"\n")
  57.  
  58. x <- seq(2.5,3.5, by = 0.01)
  59. plot(x, h(x), type ="l")
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement