SiamCafe · Blog
Bài 16 Đường Trung Bình Của Tam Giác —
บทความ

Bài 16 Đường Trung Bình Của Tam Giác —

เผยแพร่ 28 พฤษภาคม 2569

เส้นกลางของสามเหลี่ยม

เส้นกลาง Midsegment Midline สามเหลี่ยม จุดกึ่งกลาง Midpoint ขนาน ครึ่งหนึ่ง Coordinate Geometry Python คำนวณ

ทฤษฎีสูตรตัวอย่าง
Midpoint((x1+x2)/2, (y1+y2)/2)M(2,3) N(6,7) → (4,5)
Distance√((x2-x1)²+(y2-y1)²)A(0,0) B(3,4) → 5
Midsegment= ½ × ด้านที่สามด้าน=10 → เส้นกลาง=5
Area½|x1(y2-y3)+x2(y3-y1)+x3(y1-y2)|พื้นที่สามเหลี่ยม
Centroid((x1+x2+x3)/3, (y1+y2+y3)/3)จุดศูนย์ถ่วง

Python Geometry Calculator

# geometry.py — Triangle Geometry Calculator
import math
from dataclasses import dataclass
from typing import Tuple, List

@dataclass
class Point:
    x: float
    y: float

    def __repr__(self):
        return f"({self.x}, {self.y})"

def midpoint(p1: Point, p2: Point) -> Point:
    """คำนวณจุดกึ่งกลาง"""
    return Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2)

def distance(p1: Point, p2: Point) -> float:
    """คำนวณระยะทางระหว่างสองจุด"""
    return math.sqrt((p2.x - p1.x)**2 + (p2.y - p1.y)**2)

def triangle_area(a: Point, b: Point, c: Point) -> float:
    """คำนวณพื้นที่สามเหลี่ยมจากพิกัด"""
    return abs(a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)) / 2

def centroid(a: Point, b: Point, c: Point) -> Point:
    """คำนวณจุดศูนย์ถ่วง"""
    return Point((a.x + b.x + c.x) / 3, (a.y + b.y + c.y) / 3)

def midsegments(a: Point, b: Point, c: Point) -> List[Tuple[Point, Point, float]]:
    """คำนวณเส้นกลางทั้ง 3 เส้น"""
    m_ab = midpoint(a, b)  # จุดกึ่งกลาง AB
    m_bc = midpoint(b, c)  # จุดกึ่งกลาง BC
    m_ac = midpoint(a, c)  # จุดกึ่งกลาง AC

    segments = [
        (m_ab, m_bc, distance(m_ab, m_bc)),  # ขนาน AC
        (m_bc, m_ac, distance(m_bc, m_ac)),  # ขนาน AB
        (m_ab, m_ac, distance(m_ab, m_ac)),  # ขนาน BC
    ]
    return segments

# ตัวอย่าง
A = Point(0, 0)
B = Point(8, 0)
C = Point(4, 6)

print("=== Triangle Geometry ===")
print(f"  A = {A}")
print(f"  B = {B}")
print(f"  C = {C}")
print(f"\n  Sides:")
print(f"    AB = {distance(A, B):.2f}")
print(f"    BC = {distance(B, C):.2f}")
print(f"    AC = {distance(A, C):.2f}")
print(f"\n  Area = {triangle_area(A, B, C):.2f}")
print(f"  Centroid = {centroid(A, B, C)}")

print(f"\n  Midsegments:")
segs = midsegments(A, B, C)
sides = [("AC", distance(A, C)), ("AB", distance(A, B)), ("BC", distance(B, C))]
for i, (p1, p2, length) in enumerate(segs):
    side_name, side_len = sides[i]
    print(f"    {p1} → {p2} | Length = {length:.2f} "
          f"(½ of {side_name} = {side_len/2:.2f})")

Advanced Geometry

# advanced_geometry.py — Advanced Calculations
from dataclasses import dataclass
import math

@dataclass
class Triangle:
    a: Point
    b: Point
    c: Point

    @property
    def sides(self):
        return (
            distance(self.a, self.b),
            distance(self.b, self.c),
            distance(self.a, self.c),
        )

    @property
    def perimeter(self) -> float:
        return sum(self.sides)

    @property
    def area(self) -> float:
        return triangle_area(self.a, self.b, self.c)

    @property
    def area_heron(self) -> float:
        """Heron's formula"""
        a, b, c = self.sides
        s = (a + b + c) / 2
        return math.sqrt(s * (s - a) * (s - b) * (s - c))

    @property
    def incircle_radius(self) -> float:
        """รัศมีวงกลมแนบใน"""
        return self.area / (self.perimeter / 2)

    @property
    def circumcircle_radius(self) -> float:
        """รัศมีวงกลมล้อมรอบ"""
        a, b, c = self.sides
        return (a * b * c) / (4 * self.area)

    @property
    def angles_deg(self):
        """คำนวณมุมทั้ง 3 มุม (องศา)"""
        a, b, c = self.sides
        A = math.degrees(math.acos((b**2 + c**2 - a**2) / (2 * b * c)))
        B = math.degrees(math.acos((a**2 + c**2 - b**2) / (2 * a * c)))
        C = 180 - A - B
        return (round(A, 2), round(B, 2), round(C, 2))

    @property
    def triangle_type(self) -> str:
        angles = self.angles_deg
        if any(a == 90 for a in angles):
            return "Right Triangle (สามเหลี่ยมมุมฉาก)"
        elif any(a > 90 for a in angles):
            return "Obtuse Triangle (สามเหลี่ยมมุมป้าน)"
        return "Acute Triangle (สามเหลี่ยมมุมแหลม)"

tri = Triangle(Point(0, 0), Point(8, 0), Point(4, 6))

print("=== Triangle Properties ===")
a, b, c = tri.sides
print(f"  Sides: {a:.2f}, {b:.2f}, {c:.2f}")
print(f"  Perimeter: {tri.perimeter:.2f}")
print(f"  Area: {tri.area:.2f}")
print(f"  Area (Heron): {tri.area_heron:.2f}")
print(f"  Angles: {tri.angles_deg}")
print(f"  Type: {tri.triangle_type}")
print(f"  Incircle r: {tri.incircle_radius:.2f}")
print(f"  Circumcircle R: {tri.circumcircle_radius:.2f}")

# Application in IT
applications = {
    "Computer Graphics": "Transform, Rotation, Projection ใช้ Matrix + Vector",
    "Game Development": "Collision Detection ตรวจจุดอยู่ในสามเหลี่ยม",
    "GIS/Mapping": "คำนวณพื้นที่ ระยะทาง Haversine Formula",
    "Machine Learning": "Distance Metrics: Euclidean, Manhattan, Cosine",
    "CAD/CAM": "ออกแบบชิ้นส่วน Mesh Generation Tessellation",
    "Robotics": "Path Planning, Obstacle Avoidance, SLAM",
}

print(f"\n\nGeometry in IT:")
for field, desc in applications.items():
    print(f"  [{field}]: {desc}")

Visualization

# visualization.py — Triangle Visualization
# import matplotlib.pyplot as plt
# import numpy as np
#
# def plot_triangle(A, B, C):
#     fig, ax = plt.subplots(1, 1, figsize=(8, 6))
#
#     # Draw triangle
#     triangle = plt.Polygon([A, B, C], fill=False, edgecolor='blue', linewidth=2)
#     ax.add_patch(triangle)
#
#     # Draw midsegments
#     M_AB = ((A[0]+B[0])/2, (A[1]+B[1])/2)
#     M_BC = ((B[0]+C[0])/2, (B[1]+C[1])/2)
#     M_AC = ((A[0]+C[0])/2, (A[1]+C[1])/2)
#
#     for p1, p2 in [(M_AB, M_BC), (M_BC, M_AC), (M_AB, M_AC)]:
#         ax.plot([p1[0], p2[0]], [p1[1], p2[1]], 'r--', linewidth=1.5)
#
#     # Label vertices
#     for point, label in [(A, 'A'), (B, 'B'), (C, 'C')]:
#         ax.annotate(label, point, fontsize=14, ha='center', va='bottom')
#
#     # Label midpoints
#     for point, label in [(M_AB, 'M_AB'), (M_BC, 'M_BC'), (M_AC, 'M_AC')]:
#         ax.plot(*point, 'ro', markersize=6)
#         ax.annotate(label, point, fontsize=10, color='red')
#
#     ax.set_aspect('equal')
#     ax.grid(True, alpha=0.3)
#     ax.set_title('Triangle with Midsegments')
#     plt.savefig('triangle_midsegments.png', dpi=150)
#     plt.show()
#
# plot_triangle((0, 0), (8, 0), (4, 6))

# Distance Formulas for IT
formulas = {
    "Euclidean": {
        "formula": "√(Σ(xi-yi)²)",
        "use": "Straight-line distance, Default metric",
        "python": "np.linalg.norm(a - b)",
    },
    "Manhattan": {
        "formula": "Σ|xi-yi|",
        "use": "Grid-based distance, City blocks",
        "python": "np.sum(np.abs(a - b))",
    },
    "Cosine": {
        "formula": "1 - (a·b)/(|a||b|)",
        "use": "Text similarity, Embeddings",
        "python": "1 - np.dot(a, b)/(np.linalg.norm(a)*np.linalg.norm(b))",
    },
    "Haversine": {
        "formula": "2r·arcsin(√(sin²(Δφ/2)+cos(φ1)cos(φ2)sin²(Δλ/2)))",
        "use": "GPS distance on Earth surface",
        "python": "haversine(lat1, lon1, lat2, lon2)",
    },
}

print("Distance Formulas:")
for name, info in formulas.items():
    print(f"\n  [{name}]")
    for k, v in info.items():
        print(f"    {k}: {v}")

เคล็ดลับ

  • Midpoint: เฉลี่ย x และ y ของจุดปลายทั้งสอง
  • Midsegment: ขนานด้านที่สาม ยาวครึ่งหนึ่ง
  • Heron: ใช้ Heron's Formula คำนวณพื้นที่จากด้าน 3 ด้าน
  • numpy: ใช้ numpy สำหรับ Vector Operations เร็วกว่า
  • shapely: ใช้ shapely สำหรับ Complex Geometric Operations

เส้นกลางของสามเหลี่ยมคืออะไร

Midsegment เชื่อมจุดกึ่งกลางสองด้าน ขนานด้านที่สาม ยาวครึ่งหนึ่ง 3 เส้น แบ่ง 4 สามเหลี่ยมเท่ากัน