假設我有一個由兩個同心圓和一個帶有一些坐標的 numpy 陣列組成的系統。我現在想檢查坐標是否在環內,如果是,我想列印相應的值,例如 [6, 0],是嗎?我怎樣才能做到這一點?這是我到目前為止所做的,但這會導致以下錯誤:TypeError: only size-1 arrays can be convert to Python scalars
import math
import numpy as np
positions = np.array([[2.5, 8], [3, 10], [0, 5], [6, 0]])
x1 = positions[:, 0]
y1 = positions[:, 1]
# Function to check if array coordinate
# lies in the ring
def checkcircle(r, R, r1, x1, y1):
dis = int(math.sqrt(x1 * x1 y1 * y1))
return (dis-r1 >= R and dis r1 <= r)
r = 8; R = 4; r1 = 2;
if (checkcircle(r, R, r1, x1, y1)):
print([{x1}, {y1}]," yes")
else:
print("no")
uj5u.com熱心網友回復:
您的解決方案朝著正確的方向發展,直到您將點作為標量傳遞并且它們實際上是 2D numpy 陣列。我已經重寫了您的代碼,并對您的代碼做了一些修改和說明。
import math
import numpy as np
# points to check
positions = np.array([[2.5, 8], [3, 10], [0, 5], [6, 0],[2,1]])
# Function to check if points lies in the ring
def checkcircle(r, R, positions):
#initialize list to store points that lie in the ring
points_in_ring = []
# Go through every point and check its distance from center assuming, the center lies at (0,0) and can be changed later on
for i in range(positions.shape[0]):
# Calculate euclidean distance between two points
dis = math.dist(positions[i],[0.,0.])
# Print distance for more clarity
print(dis)
# If distance is more than inner radius and less than outer radius, store that point in the list
if dis > R and dis <r:
points_in_ring.append(positions[i])
return points_in_ring
r = 8; R = 4;
checkcircle(r,R, positions)
math.dist() 方法回傳兩點(p 和 q)之間的歐幾里得距離,其中 p 和 q 是該點的坐標。
注意:兩個點(p 和 q)必須具有相同的尺寸。
輸出:
8.381527307120106
10.44030650891055
5.0
6.0
2.23606797749979
[array([0., 5.]), array([6., 0.])]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436267.html
標籤:Python python-3.x 麻木的
上一篇:numpy用兩個掩碼寫
