如何找出阈值范围内满足方程2x+3y+2z=10的所有变量组合?
求解方程
10 = 2x + 3y + 2z在[-100,100]范围内的所有变量组合 问题描述
给定方程 10 = 2x + 3y + 2z,需要找出变量x、y、z在-100至100范围内的所有满足等式的组合。尝试了以下R代码但未得到结果:
set.seed(333) result = 10 # sample random values from uniform distribution x = runif(100, -100, 100) y = runif(100, -100, 100) z = runif(100, -100, 100) # store the vectors in a single dataframe df = data.frame(x, y, z) # find all the combinations of x, y and z expanded = expand.grid(df) # calculation with all the combinations expanded$result = ((expanded$x * 2) + (expanded$y * 3) + (expanded$z * 2)) == result # show the data where result is 10 expanded[expanded$result, ] [1] x y z result <0 rows> (or 0-length row.names)
原代码的问题
- 用
runif()生成的是连续随机浮点数,三个随机浮点数恰好满足等式的概率几乎为0,不可能找到符合条件的组合。 expand.grid(df)只是把三个随机向量做笛卡尔积,本质还是用随机值碰运气,完全不具备可行性。
正确实现方法
方法1:寻找整数解
方程是线性丢番图方程,可通过数学推导减少计算量:
从方程变形得:2(x+z) = 10 - 3y,所以10-3y必须是偶数,即y必须是偶数(奇数乘偶数才为偶数)。之后遍历符合条件的y,推导x和z的关系并筛选范围:
# 定义变量范围 min_val <- -100 max_val <- 100 # 初始化存储结果的数据框 solutions_int <- data.frame(x = integer(), y = integer(), z = integer()) # 遍历所有符合条件的y(偶数) for (y in seq(min_val, max_val, by = 2)) { right_part <- 10 - 3*y # 跳过10-3y为奇数的情况 if (right_part %% 2 != 0) next target_xz <- right_part %/% 2 # 遍历x的所有可能值,计算z并判断是否在范围内 for (x in min_val:max_val) { z <- target_xz - x if (z >= min_val && z <= max_val) { solutions_int <- rbind(solutions_int, data.frame(x, y, z)) } } } # 查看前5组解 head(solutions_int) # 总共有多少组整数解 nrow(solutions_int)
方法2:寻找实数解(连续值)
实数解有无穷多个,可固定x和y的取值(按指定步长生成序列),计算对应的z后筛选范围:
min_val <- -100 max_val <- 100 step <- 5 # 步长越小,生成的样本越密集 # 生成x和y的序列 x_seq <- seq(min_val, max_val, by = step) y_seq <- seq(min_val, max_val, by = step) # 生成x和y的所有组合,计算对应的z solutions_real <- expand.grid(x = x_seq, y = y_seq) solutions_real$z <- (10 - 2*solutions_real$x - 3*solutions_real$y)/2 # 筛选z在[-100,100]范围内的结果 solutions_real <- solutions_real[solutions_real$z >= min_val & solutions_real$z <= max_val, ] # 查看前5组实数解样本 head(solutions_real)
内容的提问来源于stack exchange,提问作者bird
相关产品推荐
相关产品推荐

