簡體   English   中英

計算歐幾里得距離,使用 R 遞增地將 x、y 分配給范圍循環中的素數

[英]Compute euclidean distance, incrementally assign x, y to prime numbers in range loop with R

目的

對於質數的范圍循環,分配x,y,並計算點與二維圖原點之間的距離

問題

從范圍循環內計算歐幾里得距離,moves 有質數,遞增運行,使用 j 將 moves[j] 分配給 x,然后在每個其他范圍循環中,將下一個 j moves[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

這是一種方法。
創建一個由偶數索引組成的向量來moves 即使因為計算成對進行,有效地丟棄了最后的第 25 個moves元素,因為沒有后續的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-01-07,使用reprex v2.0.2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM