gpt4 book ai didi

performance - 在 R 中的每个区间中找到函数最大值的最快方法

转载 作者:行者123 更新时间:2023-12-01 01:08:07 27 4
gpt4 key购买 nike

我有一个向量,v ,以及一个区间向量,w .我想找到一个函数的最大值,f(x) ,在每个区间。有没有比按照代码查找结果更快的方法?例如:

v = c(3.5, 2.5, 4, 6.5, 10, 2.3, 1.8, 4.7, 12, 11.5)
w = c(0, 5, 15, 20)
f = function(x){x^2}
> max = unlist(list(sapply(split(v, cut(v, w),drop = TRUE),
function(v) v[which.max(f(v))])), use.names = FALSE)
> max
[1] 4.7 12.0

最佳答案

怎么样findIntervaltapply . findInterval就像 cut ,但没有转换为因子的开销

tapply(v,findInterval(v,w),function(x)x[which.max(f(x))])
# 1 2
# 4.7 12.0

或者如果你想要最大值
tapply(f(v),findInterval(v,w),max)
# 1 2
# 22.09 144.00

或者您可以使用这样一个事实,即您的函数对于所有正值都是单调递增的。
f(tapply(v,findInterval(v,w),max))

请注意,您需要指定边界处发生的情况(阅读帮助文件)
library(microbenchmark)
microbenchmark(
mnel = tapply(v,findInterval(v,w),max),
flodel = unname(vapply(split(f(v), cut(v, w), drop = TRUE), max, numeric(1L))),
flodel2 = unname(vapply(split(seq_along(v), findInterval(v, w)), function(i, v, fv)v[i][which.max(fv[i])], numeric(1L), v, f(v))))
# Unit: microseconds
# expr min lq median uq max neval
# mnel 260.945 262.9155 264.2265 276.0645 458.670 100
# flodel 331.218 334.3585 336.0580 351.1985 694.715 100
#flodel2 124.998 127.3230 128.5170 137.0505 354.545 100

关于performance - 在 R 中的每个区间中找到函数最大值的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17158958/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com