笛卡尔坐标点间距离计算问题求助(Python实现)
Fixing Your Cartesian Coordinate Distance Calculation Code
Let's break down what's going wrong with your code and fix it step by step to get the correct pairwise distances between your 3D points.
Key Issues in Your Current Code
- No actual file reading: The line
# for line in fis commented out, so you never load any data into theframelist—it stays empty. - Function doesn't return values: Your
lengthfunction calculates distances but doesn't collect or return them, so when you calllen.append(length(frame)), you're addingNoneto the list (since functions returnNoneby default in Python if noreturnstatement exists). - Incorrect distance formula: Your expected formula has a mistake—it should be the square root of the sum of squared differences, not the sum of differences. Additionally, you're applying
sqrt()tonp.linalg.norm(), which already computes the Euclidean distance (so you're taking the square root twice, leading to wrong values). - Bad variable name: Using
lenas a variable name overrides Python's built-inlen()function, which is a bad practice. - Improper array conversion: You're converting an empty
framelist to a numpy array before loading any data.
Corrected Code
import numpy as np from math import sqrt def calculate_pairwise_distances(frame): distances = [] N = frame.shape[0] for i in range(N): for j in range(i + 1, N): # Calculate Euclidean distance: sqrt((x2-x1)² + (y2-y1)² + (z2-z1)²) # np.linalg.norm already computes this, so no need for extra sqrt() dist = np.linalg.norm(frame[j] - frame[i]) distances.append(dist) return distances # Load the coordinate data from the CSV file # Assuming your CSV has all coordinates in one line, separated by spaces with open('cartesian.csv', 'r') as f: # Read all data, split into individual numbers, convert to floats raw_data = list(map(float, f.read().split())) # Reshape into a Nx3 array (each row is x, y, z) frame = np.array(raw_data).reshape(-1, 3) # Calculate all pairwise distances distance_list = calculate_pairwise_distances(frame) # Write results to output.txt with open('output.txt', 'w') as g: for dist in distance_list: g.write(f"{dist}\n")
Important Explanations
- File Reading: The code reads all the coordinate data at once, splits it into individual numerical values, then reshapes it into a numpy array where each row represents a single (x, y, z) point. This works for your sample data where all coordinates are in a single line separated by spaces.
- Distance Calculation: The
calculate_pairwise_distancesfunction collects all distances between unique pairs (i,j where j > i) in a list and returns it. We usenp.linalg.norm()directly since it computes the correct Euclidean distance for 3D vectors. - File Writing: We use
with open(...)for both reading and writing files—this ensures files are properly closed without needing explicitclose()calls. - Variable Names: Renamed
lengthtocalculate_pairwise_distancesfor clarity, andlentodistance_listto avoid overriding the built-in function.
If your CSV file has each point on a separate line instead of one line, you can adjust the reading part to:
frame = [] with open('cartesian.csv', 'r') as f: for line in f: # Skip empty lines if any if line.strip(): coords = list(map(float, line.strip().split())) frame.append(coords) frame = np.array(frame)
内容的提问来源于stack exchange,提问作者user12858479
相关产品推荐
相关产品推荐

