[R] Solving a system of two equations

Berend Hasselman bhh at xs4all.nl
Mon Sep 10 09:05:43 CEST 2012


On 10-09-2012, at 01:22, berg1546 wrote:

> Hi,
> 
> I am trying to find a simple way to numerically solve a system of two
> equations equal to zero with two unknowns (x_loc and y_loc). Here is a mock
> data set and below it, the equations I need to solve.
> 
> theta<-c(180,135,90)/(2*pi)
> x<-c(0,0,15)
> y<-c(20,0,0)
> 
> 0 =
> -sum((y_loc-y)*(sin(theta)*(x_loc-x)-cos(theta)*(y_loc-y))/(((x_loc-x)^2+(y_loc-y)^2)^0.5)^3)
> 0 =
> -sum((x_loc-x)*(sin(theta)*(x_loc-x)-cos(theta)*(y_loc-y))/(((x_loc-x)^2+(y_loc-y)^2)^0.5)^3)

You can use package nleqslv for solving systems of nonlinear equations.
Example for your system:

library(nleqslv)

theta<-c(180,135,90)/(2*pi)
x<-c(0,0,15)
y<-c(20,0,0)

f <- function(par) {
    fval  <- numeric(length(par))
    x_loc <- par[1]
    y_loc <- par[2]

    fval[1] <- -sum((y_loc-y)*(sin(theta)*(x_loc-x)-cos(theta)*(y_loc-y))/(((x_loc-x)^2+(y_loc-y)^2)^0.5)^3)
    fval[2] <- -sum((x_loc-x)*(sin(theta)*(x_loc-x)-cos(theta)*(y_loc-y))/(((x_loc-x)^2+(y_loc-y)^2)^0.5)^3)

    fval
}

nleqslv(c(17,17), f)

I haven't got a clue about good starting values.
I get the impression is that your system is quite sensitive.
nleqslv finds a solution but it is very different from the starting value. It's up to you to verify the correctness of your system.

You can simplify the computation in your function by computing the common subexpressions only once

f1 <- function(par) {
    fval  <- numeric(length(par))
    x_loc <- par[1]
    y_loc <- par[2]
    
    A <- (sin(theta)*(x_loc-x)-cos(theta)*(y_loc-y))
    B <- (((x_loc-x)^2+(y_loc-y)^2)^0.5)^3
    C <- A/B
    fval[1] <- -sum((y_loc-y)*C)
    fval[2] <- -sum((x_loc-x)*C)

    fval
}    


Berend




More information about the R-help mailing list