In: Computer Science
The columns of the input file correspond to the point coordinates, for example, the first column provides the coordinates of the first point and the column length indicates whether it is 2D vs. 3D. First, compute the area of the triangle (the first line of your output file). Second, using the first two points, construct a line if 2D or a plane if 3D (the bisector of the two points) and find the distance of the third point to that line or plane (the second line of your output file). The output should have two numbers in separate lines. The output should contain numbers with up to four significant digits.
The input for Part C can be a 2x3 matrix or alternatively a 3x3 matrix. Your program should be able to process both input file formats.
Input format (3x3 matrix):
n11 n12 n13
n21 n22 n23
n31 n32 n33
In python please
Reading the 3 points as in the matrix to lists from input text file, mydata.txt
first_point = []
second_point = []
third_point = []
with open("/content/mydata.txt") as file:
lines = [line.strip() for line in file]
for i in range(len(lines)):
row = lines[i].split(" ")
first_point.append(int(row[0]))
second_point.append(int(row[1]))
third_point.append(int(row[2]))
print(first_point,second_point,third_point)
Function to compute the distance between two points
def distance(p1,p2):
if len(p1) == 3:
d = math.sqrt(math.pow(p1[0] - p2[0], 2) +
math.pow(p1[1] - p2[1], 2) +
math.pow(p2[2] - p2[2], 2)* 1.0)
else:
d = math.sqrt(math.pow(p1[0] - p2[0], 2) +
math.pow(p1[1] - p2[1], 2)* 1.0)
print(d)
return d
Computing the area of the triangle formed by the 3 points
d1 = distance(first_point,second_point)
d2 = distance(second_point,third_point)
d3 = distance(third_point,second_point)
p = (d1 + d2 + d3)/2
area = math.sqrt(p * (p - d1) * (p - d2) * (p - d3))
using the first two points, construct a line if 2D or a plane if 3D (the bisector of the two points) and find the distance of the third point to that line or plane (the second line of your output file)
import numpy as np
p1 = np.array(first_point)
p2 = np.array(second_point)
p3 = np.array(third_point)
if len(lines) == 2:
a = p2[1] - p1[1]
b = p1[0] - p2[0]
c = a*(p1[0]) + b*(p1[1])
dist = abs((a * p3[0] + b * p3[1] + c)) / (math.sqrt(a * a + b * b))
if len(lines) == 3:
# These two vectors are in the plane
v1 = p3 - p1
v2 = p2 - p1
# the cross product is a vector normal to the plane
cp = np.cross(v1, v2)
a,b,c = cp
# This evaluates a * x3 + b * y3 + c * z3 which equals d
d = np.dot(cp, p3)
d = abs((a * p3[0] + b * p3[1] + c * p3[2] + d))
e = (math.sqrt(a * a + b * b + c * c))
dist = d/e
writing the area and the distance into output file
f = open('output.txt', 'w+')
f.write("%4f\n" % area)
f.write("%4f\n" % dist)