用 R 求解联立方程

发布于 2024-12-15 15:28:44 字数 200 浏览 3 评论 0原文

假设我有以下方程:

 x + 2y + 3z = 20  
2x + 5y + 9z = 100  
5x + 7y + 8z = 200

如何解出这些方程的 xyz?如果可能的话,我想使用 R 或任何其他计算机工具来求解这些方程。

Suppose I have the following equations:

 x + 2y + 3z = 20  
2x + 5y + 9z = 100  
5x + 7y + 8z = 200

How do I solve these equations for x, y and z? I would like to solve these equations, if possible, using R or any other computer tools.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

有深☉意 2024-12-22 15:28:44

这应该有效

A <- matrix(data=c(1, 2, 3, 2, 5, 9, 5, 7, 8), nrow=3, ncol=3, byrow=TRUE)    
b <- matrix(data=c(20, 100, 200), nrow=3, ncol=1, byrow=FALSE)
round(solve(A, b), 3)

     [,1]
[1,]  320
[2,] -360
[3,]  140

This should work

A <- matrix(data=c(1, 2, 3, 2, 5, 9, 5, 7, 8), nrow=3, ncol=3, byrow=TRUE)    
b <- matrix(data=c(20, 100, 200), nrow=3, ncol=1, byrow=FALSE)
round(solve(A, b), 3)

     [,1]
[1,]  320
[2,] -360
[3,]  140
冷心人i 2024-12-22 15:28:44

为了清楚起见,我修改了之前答案中构造矩阵的方式。

a <- rbind(c(1, 2, 3), 
           c(2, 5, 9), 
           c(5, 7, 8))
b <- c(20, 100, 200)
solve(a, b)

如果我们需要显示分数:

library(MASS)
fractions(solve(a, b))

For clarity, I modified the way the matrices were constructed in the previous answer.

a <- rbind(c(1, 2, 3), 
           c(2, 5, 9), 
           c(5, 7, 8))
b <- c(20, 100, 200)
solve(a, b)

In case we need to display fractions:

library(MASS)
fractions(solve(a, b))
很快妥协 2024-12-22 15:28:44

另一种方法是使用 lm 对方程进行建模,如下所示:

lm(b ~ . + 0, 
   data = data.frame(x = c(1, 2, 5), 
                     y = c(2, 5, 7), 
                     z = c(3, 9, 8), 
                     b = c(20, 100, 200)))

它会产生相同的

Coefficients:
   x     y     z  
 320  -360   140

如果您使用 tibble 包,您甚至可以让它像原始方程一样读取:

lm(b ~ . + 0, 
   tibble::tribble(
     ~x, ~y, ~z,  ~b,
      1,  2,  3,  20,
      2,  5,  9, 100,
      5,  7,  8, 200))

结果输出。

Another approach is to model the equations using lm as follows:

lm(b ~ . + 0, 
   data = data.frame(x = c(1, 2, 5), 
                     y = c(2, 5, 7), 
                     z = c(3, 9, 8), 
                     b = c(20, 100, 200)))

which produces

Coefficients:
   x     y     z  
 320  -360   140

If you use the tibble package you can even make it read just like the original equations:

lm(b ~ . + 0, 
   tibble::tribble(
     ~x, ~y, ~z,  ~b,
      1,  2,  3,  20,
      2,  5,  9, 100,
      5,  7,  8, 200))

which produces the same output.

渡你暖光 2024-12-22 15:28:44
A <- matrix(data=c(1, 2, 3, 2, 5, 9, 5, 7, 8),nrow=3,ncol=3,byrow=TRUE)    
b <- matrix(data=c(20, 100, 200),nrow=3,ncol=1,byrow=FALSE)
solve(A)%*% b

请注意,这是一个方阵!

A <- matrix(data=c(1, 2, 3, 2, 5, 9, 5, 7, 8),nrow=3,ncol=3,byrow=TRUE)    
b <- matrix(data=c(20, 100, 200),nrow=3,ncol=1,byrow=FALSE)
solve(A)%*% b

Note that this is a square matrix!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文