gpt4 book ai didi

从列表中舍入到最接近的任意数字

转载 作者:行者123 更新时间:2023-12-03 23:26:36 26 4
gpt4 key购买 nike

我基本上是在寻找一种方法来做 this Ruby script 的变体在 R。
我有一个 任意数字列表 (在这种情况下,回归图的主持人的步骤)彼此之间的距离不等,我想将这些数字周围范围内的值四舍五入到列表中最接近的数字。
范围不重叠。

arbitrary.numbers <- c(4,10,15) / 10
numbers <- c(16:1 / 10, 0.39, 1.45)
range <- 0.1

预期输出:
numbers
## 1.6 1.5 1.4 1.3 1.2 1.1 1.0 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0.39 1.45
round_to_nearest_neighbour_in_range(numbers,arbitrary.numbers,range)
## 1.5 1.5 1.5 1.3 1.2 1.0 1.0 1.0 0.8 0.7 0.6 0.4 0.4 0.4 0.2 0.1 0.4 1.5

我有一个小辅助函数可以解决我的特定问题,但它不是很灵活,并且包含一个循环。我可以在这里发布它,但我认为真正的解决方案看起来会完全不同。

为速度计时的不同答案(在一百万个数字上)
> numbers = rep(numbers,length.out = 1000000)
> system.time({ mvg.round(numbers,arbitrary.numbers,range) })[3]
elapsed
0.067
> system.time({ rinker.loop.round(numbers,arbitrary.numbers,range) })[3]
elapsed
0.289
> system.time({ rinker.round(numbers,arbitrary.numbers,range) })[3]
elapsed
1.403
> system.time({ nograpes.round(numbers,arbitrary.numbers,range) })[3]
elapsed
1.971
> system.time({ january.round(numbers,arbitrary.numbers,range) })[3]
elapsed
16.12
> system.time({ shariff.round(numbers,arbitrary.numbers,range) })[3]
elapsed
15.833
> system.time({ mplourde.round(numbers,arbitrary.numbers,range) })[3]
elapsed
9.613
> system.time({ kohske.round(numbers,arbitrary.numbers,range) })[3]
elapsed
26.274

MvG 的函数是最快的,大约比 Tyler Rinker 的第二个函数快 5 倍。

最佳答案

一个矢量化的解决方案,没有任何 apply家庭功能或循环:

关键是findInterval ,它在 arbitrary.numbers 中找到“空间”其中 numbers 中的每个元素在。。。之间”。所以,findInterval(6,c(2,4,7,8))返回 2 , 因为 6位于 c(2,4,7,8) 的第二个和第三个索引之间.

# arbitrary.numbers is assumed to be sorted.
# find the index of the number just below each number, and just above.
# So for 6 in c(2,4,7,8) we would find 2 and 3.
low<-findInterval(numbers,arbitrary.numbers) # find index of number just below
high<-low+1 # find the corresponding index just above.

# Find the actual absolute difference between the arbitrary number above and below.
# So for 6 in c(2,4,7,8) we would find 2 and 1.
# (The absolute differences to 4 and 7).
low.diff<-numbers-arbitrary.numbers[ifelse(low==0,NA,low)]
high.diff<-arbitrary.numbers[ifelse(high==0,NA,high)]-numbers

# Find the minimum difference.
# In the example we would find that 6 is closest to 7,
# because the difference is 1.
mins<-pmin(low.diff,high.diff,na.rm=T)
# For each number, pick the arbitrary number with the minimum difference.
# So for 6 pick out 7.
pick<-ifelse(!is.na(low.diff) & mins==low.diff,low,high)

# Compare the actual minimum difference to the range.
ifelse(mins<=range+.Machine$double.eps,arbitrary.numbers[pick],numbers)
# [1] 1.5 1.5 1.5 1.3 1.2 1.0 1.0 1.0 0.8 0.7 0.6 0.4 0.4 0.4 0.2 0.1 0.4 1.5

关于从列表中舍入到最接近的任意数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12861061/

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