我有一个代码可以评估 4 个联立方程的参数值。当 a + b(存储在 results$ab 中)大于 3000 时,我特别有兴趣存储所有参数组合。如果大于 3000,则将其编码为"is"。我想编写一个 for 循环,循环遍历代码以检查是否 a + b > 3000 并存储相应的值。然后,我希望程序循环 1000 次,并存储相应"is"的参数值。我正在尝试存储输出,但它没有给我任何结果。

x <- seq(from = 0.0001, to = 1000, by = 0.1)
t <- seq(from = 0.0001, to = 1000, by = 0.1)
v <- seq(from = 0.0001, to = 1000, by = 0.1)
w <- seq(from = 0.0001, to = 1000, by = 0.1)
n <- seq(from = 0.0001, to = 1000, by = 0.1)
f <- seq(from = 0.0001, to = 1000, by = 0.1)


  values <- list(x = x, t = t, v = v, w = w, n = n, f = f)
  for(i in 1:1000){
    eqs <- list(
      a = expression(x * t - 2 * x),
      b = expression(v - x^2),
      c = expression(x - w*t - t*t),
      d = expression((n - f)/t)
    )

    for(i in 1:1000){
    samples <- 10000
    values.sampled <- lapply(values, sample, samples)
    results[i] <- sapply(eqs, eval, envir = values.sampled)
    results[i] <- data.frame(results)
    results$ab[i] <- results$a[i] + results$b[i]
    results$binary[i] <- ifelse(results$ab[i] > 3000, "Yes","No")
    output[i] <- results[results$binary=="Yes",]

  }

what <- as.list(output)

最佳答案

a+b 等于 (x * t - 2 * x) + (v - x^2) ,它只是 x 的二次方,因此您可以解析 a+b>3000xvt

不等式是 x^2 + (2-t)x + (3000-v) < 0

替换 T = 2-tV = 3000-v ,然后替换 x^2 + Tx + V < 0

对于任何小于零的值,它必须有两个实数根,这意味着T^2 - 4V > 0 - 即 V < (T^2)/4 。 ( https://en.wikipedia.org/wiki/Quadratic_formula )

给定 TV 满足这个不等式,xa+b>3000 的值是二次根之间的值,即 |2x+T| < sqrt(T^2 - 4V)

因此,如果您想要选择满足条件的值,则应该直接循环遍历 t 的一系列值,选择满足 vV < (T^2)/4 值,然后选择落在适当范围内的 x

这是一种方法...

t <- 1:1000
T <- 2 - t
V <- sapply((T ^ 2) / 4, function(z) runif(min = 0, max = z, n = 1)) #assumes V>0 (???)
v <- 3000 - V
x <- (sapply(sqrt(T ^ 2 - 4 * V), function(z) runif(min = -z, max = z, n = 1)) - T) / 2
ab <- (x * t - 2 * x) + (v - x ^ 2) #all >3000 (except for t=2, where ab=3000 exactly)

关于r - 重新采样R中联立方程的参数值时如何存储循环的输出?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58275295/

10-12 17:13