Search code examples
rmathematical-optimizationdifferential-equations

Plot and solve an equation in R


I want to find the value of u that minimizes my equation (least squares) sum(w*(x-u)^2)

Is is possible to plot this equation in R? This would probably let me visually pick the value u that minimizes the equation.

Is is also possible to solve for u value that minimizes the equations?

x <- c(0.18, -1.54, 0.42, 0.95)
w <- c(2, 1, 3, 1)
sum(w*(x-u)^2)

Solution

  • In general, if you want to optimize a function for a single parameter, you can use the optimize function

    x <- c(0.18, -1.54, 0.42, 0.95)
    w <- c(2, 1, 3, 1)
    
    optimize( function(u){ sum(w*(x-u)^2) }, interval=c(-100,100))
    
    # $minimum
    # [1] 0.1471429
    # 
    # $objective
    # [1] 3.716543
    

    If you want, you can plot this objective function for different values of u as well. Here we define a function of u (we use sapply because otherwise the sum() would collapse the results when running the function for multiple points) and plot it using curve()

    obj <- function(U){sapply(U, function(u) sum(w*(x-u)^2))}
    curve(obj, from=-2, to=2)
    

    and you can see the minimum occurs near 0.1471429.

    enter image description here