计算欧氏距离,在带R的范围循环中递增地将x,y赋值为素数

tquggr8v  于 2023-01-10  发布在  其他
关注(0)|答案(1)|浏览(102)

目的

对素数进行range循环,赋值x,y,计算点与点到原点的距离

问题

从range循环中计算欧氏距离,移动数为质数,递增运行,使用j将移动数[j]分配给x,然后在每隔一个range循环中,将接下来的j个移动数[j +1]分配给y。序列应为x = 2 y = 3 x = 5 y = 7 x = 11 y = 13 x = 17 y = 19 x = 23 y = 29 x = 31 y = 37...x = 89 y = 97。然后每对x、y应该计算欧几里德距离。
编号

euclidean <- function(x, y) sqrt(sum((x - y)^2))

x = 0
y = 0
s = (NULL)
for (j in range(length(moves)-1)) {
  if ((j %% 2) == 0) {
    x <- moves[j]
  } else {
    y <- moves[j+1]
  }
  append(s, euclidean(x,y))
  print(euclidean(x,y)) # just a test!
  j=+1
}
output:
[1] 86
[1] 86

质数的数据

moves
 2  3  5  7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
ifmq2ha2

ifmq2ha21#

这里有一个办法。
创建moves的偶数索引向量。即使计算是成对进行的,也会有效地丢弃moves的最后一个元素,即第25个元素,因为后面没有y。然后,在sapply循环中对每对元素调用euclidean,一行程序将完成此操作。

# data
moves <- scan(text = "
2  3  5  7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
")
moves
#>  [1]  2  3  5  7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

euclidean <- function(x, y) sqrt(sum((x - y)^2))

inx <- seq_along(moves)[c(FALSE, TRUE)]
inx
#>  [1]  2  4  6  8 10 12 14 16 18 20 22 24

sapply(inx, \(i) euclidean(moves[i - 1L], moves[i]))
#>  [1] 1 2 2 2 6 6 2 6 2 4 6 6

创建于2023年1月7日,使用reprex v2.0.2

相关问题