gpt4 book ai didi

r - 如何检查数字序列是否单调递增(或递减)?

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

我们得到一个数字序列,作为向量foo。任务是找到 foo单调递增 - 每一项都小于或等于下一项 - 或单调递减 - 每一项大于或等于下一个。

当然可以通过循环找到这个,但是还有更多创意吗?

最佳答案

另一个:检查是否

all(x == cummax(x))

all(x == cummin(x))

分别表示单调增加或单调减少。看起来 cummaxdiff 快很多,而且使用的内存也更少:

> x <- seq_len(1e7)
> system.time(all(x == cummax(x)))
user system elapsed
0.11 0.00 0.11
> system.time(all(diff(x) >= 0))
user system elapsed
0.47 0.13 0.59

> x <- seq_len(1e8)
> system.time(all(x == cummax(x)))
user system elapsed
1.06 0.09 1.16
> system.time(all(diff(x) >= 0))
Error: cannot allocate vector of size 381.5 Mb
In addition: Warning messages:
1: Reached total allocation of 1535Mb: see help(memory.size)
2: Reached total allocation of 1535Mb: see help(memory.size)
3: Reached total allocation of 1535Mb: see help(memory.size)
4: Reached total allocation of 1535Mb: see help(memory.size)
Timing stopped at: 1.96 0.38 2.33

我敢打赌为什么 cummaxdiff 更快,因为它只需要比较数字,这比计算差异更快。

编辑:根据您(阿里)的要求,进行其他测试,包括您的答案(请注意,我现在正在不同的计算机上运行,​​因此以下结果不应与上面的结果进行比较)

> x <- seq_len(1e7)
> system.time(x == cummax(x))
user system elapsed
0.316 0.096 0.416
> system.time(all(diff(x) >= 0))
user system elapsed
4.364 0.240 4.632
> system.time(x[-1] - x[-length(x)] >= 0)
user system elapsed
3.828 0.380 4.227
> system.time(all(x[-1] >= x[-length(x)]))
user system elapsed
2.572 0.288 2.865

关于r - 如何检查数字序列是否单调递增(或递减)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13093912/

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