寻根函数中不一致的参数错误

时间:2018-07-02 13:16:06

标签: python r function syntax-error

我正在尝试求解x in:

R中的两个实现:

H <- diag(2)  # 2-dimensional diagonal matrix with ones on the diagonal
uniroot.all(function(x, y, H) {c(t(x)) %*% solve(H) %*% c(x) - y}, y=y, H=H, lower=0, upper=10) 
uniroot.all(function(x, y, H) {t(x) %*% solve(H) %*% x - y}, y=y, H=H, lower=0, upper=10) 

但是,两者都给出相同的不合格参数错误:

Error in c(t(x)) %*% solve(H) : non-conformable arguments
Error in t(x) %*% solve(H) : non-conformable arguments

我理解错误,但也许有人可以阐明如何在上述等式中求解x,因为我没有找到解决方案(R或Python可以)

提前谢谢您。

1 个答案:

答案 0 :(得分:1)

会有许多满足条件的值。例如,以H为单位矩阵而y为5为例,则x可以是c(1,2)或(2,1)或(1.656615,1.501874)或(2.2184971,0.2797686)等。形成椭圆形,溶胶为5:

因此我们可以做到:

 optim(c(0,1.9),function(x,H,y)abs(c(crossprod(x,solve(H,x)))-y),H=diag(2),y=5)

您可以测试以上代码给出的解决方案,您会发现它们实际上给出了5.选择任何起始值:

s=function(w,u)optim(c(w,u),function(x,H,y)abs(c(crossprod(x,solve(H,x)))-y),H=diag(2),y=5)$par
a=1:4
r=t(mapply(s,a,rep(a,each=length(a))))
cbind(r,rowSums(r^2))
           [,1]      [,2] [,3]
 [1,] 1.2216786 1.8728325    5
 [2,] 2.0000000 1.0000000    5
 [3,] 1.1964828 1.8890286    5
 [4,] 0.2209853 2.2251215    5
 [5,] 1.0000000 2.0000000    5
 [6,] 1.6566155 1.5018739    5
 [7,] 0.1675176 2.2297843    5
 [8,] 1.2257806 1.8701503    5
 [9,] 1.8890286 1.1964828    5
[10,] 2.2297843 0.1675176    5
[11,] 1.6043461 1.5575857    5
[12,] 1.2658540 1.8432617    5
[13,] 2.2251215 0.2209853    5
[14,] 1.8701503 1.2257806    5
[15,] 1.8432617 1.2658540    5
[16,] 1.6636298 1.4941003    5

您看到他们都给了您5。