Home > database >  Solve simple equations with unknown value in right side
Solve simple equations with unknown value in right side

Time:08-19

I want to find the x values in equation y = 2*x 100 when y varies from 200 to 250. I have the F1 function but it does not work. I don't want to change the structure of equation to (y-100)/2 as the main equation is too complex. any help would be appreciated.

F1 <- function(y){
  y = 2*x 100
  return(x)
}

F1(200:250)

CodePudding user response:

By simply rearranging the formula y = 2 * x 100 to solve for x, we have x = (y - 100)/2, so you could do:

 F1 <- function(y) (y - 100)/2 

F1(200:250)
#>  [1] 50.0 50.5 51.0 51.5 52.0 52.5 53.0 53.5 54.0 54.5 55.0 55.5 56.0
#> [14] 56.5 57.0 57.5 58.0 58.5 59.0 59.5 60.0 60.5 61.0 61.5 62.0 62.5
#> [27] 63.0 63.5 64.0 64.5 65.0 65.5 66.0 66.5 67.0 67.5 68.0 68.5 69.0
#> [40] 69.5 70.0 70.5 71.0 71.5 72.0 72.5 73.0 73.5 74.0 74.5 75.0

And check this works by feeding these back in to our original equation, with the above numbers given as the values of x. This should return 200:250

x <- F1(200:250)
 
2 * x   100
#>  [1] 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
#> [17] 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
#> [33] 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
#> [49] 248 249 250

For a more general solution, suppose we have your original function:

F0 <- function(x) x * 2   100

We can define a solver that reverses the function to find the x value that gives a particular value of y by using uniroot.

find_x_for_given_y <- function(y, func) {
  
  sapply(y, function(y_i) {
    uniroot(function(x) func(x) - y_i, c(-1e6, 1e6))$root
  })
}

So, to find the values which, when passed to F0 give the values 200:250, we can do:

find_x_for_given_y(200:250, F0)
#>  [1] 50.0 50.5 51.0 51.5 52.0 52.5 53.0 53.5 54.0 54.5 55.0 55.5 56.0
#> [14] 56.5 57.0 57.5 58.0 58.5 59.0 59.5 60.0 60.5 61.0 61.5 62.0 62.5
#> [27] 63.0 63.5 64.0 64.5 65.0 65.5 66.0 66.5 67.0 67.5 68.0 68.5 69.0
#> [40] 69.5 70.0 70.5 71.0 71.5 72.0 72.5 73.0 73.5 74.0 74.5 75.0

Of course, this is the same as above, but is at least generalized to accept any function of one variable.

CodePudding user response:

You could use uniroot() to search for the root of a function.

F1 <- function(x, y) {
  2 * x   100 - y
}

sapply(200:250, \(y) uniroot(F1, c(0, 1), y = y, extendInt = "yes")$root)

#  [1] 50.0 50.5 51.0 51.5 52.0 52.5 53.0 53.5 54.0 54.5 55.0 55.5 56.0 56.5 57.0 57.5 58.0
# [18] 58.5 59.0 59.5 60.0 60.5 61.0 61.5 62.0 62.5 63.0 63.5 64.0 64.5 65.0 65.5 66.0 66.5
# [35] 67.0 67.5 68.0 68.5 69.0 69.5 70.0 70.5 71.0 71.5 72.0 72.5 73.0 73.5 74.0 74.5 75.0
  • Related