r - 对 min() 函数进行积分会得到与内部函数不同的结果

标签 r integration min integral integrate

这两个结果不应该是一样的吗?为什么他们不呢?

integrate(\(x) {x * min(-x+10, 10)},lower = 0, upper = 10)$value
> [1] 1.085709

integrate(\(x) {x * (-x+10)},lower = 0, upper = 10)$value
> [1] 166.6667

请记住,从 x 值 0 到 10,我们永远不应该期望得到高于 10 的 y = -x + 10 值,因此 min(-x+10, 10) 将始终返回 (- x+10) 只要我们在 0 到 10 之间。因此这两个积分应该是相同的。

为什么不呢?

最佳答案

问题是 min 仅返回一个值,它没有矢量化。

f <- \(x) {x * min(-x+10, 10)}
g <- \(x) {x * (-x + 10)}

f <- Vectorize(f, "x")
g <- Vectorize(g, "x")

# curve(f, from = 0, to = 10)
# # this overplots perfectly
# curve(g, from = 0, to = 10, add = TRUE, col = "red")

integrate(f, lower = 0, upper = 10)$value
#> [1] 166.6667
integrate(g, lower = 0, upper = 10)$value
#> [1] 166.6667

创建于 2023 年 8 月 21 日 reprex v2.0.2


编辑

如果您不想两次分配相同的名称,第一次创建函数,第二次对其进行向量化,请使用新的管道运算符。

f <- (\(x) {x * min(-x+10, 10)}) |> Vectorize()
g <- (\(x) {x * (-x + 10)}) |> Vectorize()

创建于 2023 年 8 月 21 日 reprex v2.0.2

关于r - 对 min() 函数进行积分会得到与内部函数不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76947771/

相关文章:

r - 在RStudio中创建良好的有线输出

单页应用程序的javascript集成测试

python - 将数组中的低值归零的最快方法?

python - 为什么我不断收到错误 "min() arg is an empty sequence"?

r - 为什么在 R 代码中添加多个条件时使用 '$"(美元符号)?

r - 根据其他变量中的条件值,通过一个变量对 data.table 进行子集化

Spring Integration,删除出站 channel 适配器中的文件

gmail - 发送或接收电子邮件时发送 webhook

javascript - 帮助 if 语句 - 最少 3 个字符

r - 当条目本身的值为零且条目之前的条目为 0 时,跳过 Paste0 条目