# 如何根据R中函数的结果找到x的值

##### 问题描述投票：0回答：2

``````a_vector<-seq(1:10)
``````

``````my_function<-function(a){
a*sqrt(5)
}

b_vector<-my_function(a_vector)

b_vector
``````

2.236068 4.472136 6.708204 8.944272 11.180340 13.416408 15.652476 17.888544 20.124612 22.360680

r
##### 2个回答
0

``uniroot``

``uniroot``

``b = sqrt(5) * a``

``0 = b - sqrt(5) * a``

``````solve_fn <- function(a, b){
b - a * sqrt(5)
}

uniroot(f = solve_fn,
interval = c(-1e8, 1e8), # search interval, a numeric range.
b = 10)

\$root
[1] 4.472136

\$f.root
[1] -1.354202e-08

\$iter
[1] 2

\$init.it
[1] NA

\$estim.prec
[1] 6.103516e-05
``````

``a = 4.472136``

``b = 10``

0

`optim`

` 反转（某些）函数，例如，如果我们定义此函数：`

```reverse_fun <- function(fun, output) { unlist(lapply(output, function(x) { suppressWarnings(optim(x, \(y) abs(x - fun(y)))\$par) })) } ```

```b_vector <- c(2.236068, 4.472136, 6.708204, 8.944272, 11.180340, 13.416408, 15.652476, 17.888544, 20.124612, 22.360680) my_function <- function(a) { a * sqrt(5) } reverse_fun(my_function, b_vector) #> [1] 1 2 3 4 5 6 7 8 9 10 ```
`    `