Sure! Below is a Python script that fulfills your requirements. This script:
- Generates points on a circle based on the user-specified number.
- Accepts line definitions as pairs of point indices.
- Computes intersection points of the infinite lines defined by these pairs.
- Determines which intersections lie outside the circle.
- Plots two graphs:
- One showing only the intersection points outside the circle.
- Another showing the infinite lines along with their intersection points.
- Outputs detailed information about each intersection point outside the circle, including which original lines define them.
- Displays the total number of such intersection points.
Here's the complete script:
import matplotlib.pyplot as plt
import math
import itertools
def get_circle_points(N, radius=1):
"""
Generate N points evenly spaced on a circle with the given radius.
"""
points = []
for i in range(N):
angle = 2 * math.pi * i / N
x = radius * math.cos(angle)
y = radius * math.sin(angle)
points.append((x, y))
return points
def input_line_segments(N):
"""
Input line segments as pairs of point indices.
"""
print("Zadejte úsečky jako dvojice indexů bodů ve formátu (cislo, cislo).")
print("Například: (1,3)")
print("Zadejte 'done' pro dokončení.")
segments = []
while True:
s = input("Zadejte úsečku: ")
if s.lower() == 'done':
break
try:
s = s.strip()
if not (s.startswith('(') and s.endswith(')')):
raise ValueError
s = s.strip('()')
parts = s.split(',')
if len(parts) != 2:
raise ValueError
idx1, idx2 = map(int, parts)
if not (1 <= idx1 <= N and 1 <= idx2 <= N):
raise ValueError
if idx1 == idx2:
raise ValueError("Indexy musí být různé.")
segments.append((idx1 - 1, idx2 - 1)) # Zero-based indexing
except ValueError:
print("Neplatný vstup. Zadejte dvě různá celá čísla oddělená čárkou a uzavřená v závorkách, např. (1,3).")
return segments
def compute_line_coefficients(p1, p2):
"""
Compute the coefficients A, B, C of the line equation Ax + By = C given two points.
"""
x1, y1 = p1
x2, y2 = p2
A = y2 - y1
B = x1 - x2
C = A * x1 + B * y1
return A, B, C
def compute_intersection(l1, l2):
"""
Compute the intersection point of two lines given by coefficients A, B, C.
Returns (x, y) or None if lines are parallel.
"""
A1, B1, C1 = l1
A2, B2, C2 = l2
determinant = A1 * B2 - A2 * B1
if determinant == 0:
return None # Parallel lines
x = (B2 * C1 - B1 * C2) / determinant
y = (A1 * C2 - A2 * C1) / determinant
return (x, y)
def is_outside_circle(point, radius=1, tol=1e-9):
"""
Check if a point is outside the circle with the given radius.
"""
x, y = point
distance_sq = x**2 + y**2
return distance_sq > (radius ** 2) + tol
def plot_circle(ax, points, radius=1):
"""
Plot the unit circle and the points on it.
"""
circle = plt.Circle((0, 0), radius, fill=False, color='black', linestyle='dashed')
ax.add_artist(circle)
for idx, (x, y) in enumerate(points):
ax.plot(x, y, 'ko')
ax.text(x * 1.05, y * 1.05, str(idx + 1), fontsize=12, ha='center', va='center')
def plot_lines(ax, lines, color='blue', linewidth=1, linestyle='-'):
"""
Plot infinite lines by extending them to a large range.
"""
range_limit = 10 # Extend lines far beyond the circle
for line in lines:
A, B, C = line
if B != 0:
x_vals = [-range_limit, range_limit]
y_vals = [(C - A * x) / B for x in x_vals]
else:
# Vertical line
x = C / A
y_vals = [-range_limit, range_limit]
x_vals = [x, x]
ax.plot(x_vals, y_vals, color=color, linewidth=linewidth, linestyle=linestyle)
def plot_intersections(ax, points):
"""
Plot intersection points.
"""
for pt in points:
ax.plot(pt[0], pt[1], 'ro')
def main():
print("=== Geometrický Program na Zjišťování Průsečíků ===")
# Step 1: Input number of points
try:
N = int(input("Zadejte počet bodů na kružnici: "))
if N < 2:
print("Počet bodů musí být alespoň 2.")
return
except ValueError:
print("Neplatný vstup. Zadejte celé číslo.")
return
# Step 2: Generate points on the circle
points = get_circle_points(N)
# Step 3: Input line segments
segments = input_line_segments(N)
if len(segments) < 2:
print("Pro nalezení průsečíků je potřeba alespoň 2 úsečky.")
return
# Step 4: Compute line coefficients
lines = []
for idx, (i, j) in enumerate(segments, start=1):
p1 = points[i]
p2 = points[j]
coeffs = compute_line_coefficients(p1, p2)
lines.append({'indices': (i, j), 'coefficients': coeffs, 'label': f"Line {idx} ({i+1}-{j+1})"})
# Step 5: Compute intersections of all line pairs
intersections = {}
intersection_details = []
for line1, line2 in itertools.combinations(lines, 2):
intersect_pt = compute_intersection(line1['coefficients'], line2['coefficients'])
if intersect_pt is not None:
if is_outside_circle(intersect_pt):
key = (round(intersect_pt[0], 9), round(intersect_pt[1], 9))
if key not in intersections:
intersections[key] = intersect_pt
intersection_details.append({
'point': intersect_pt,
'lines': (line1['label'], line2['label'])
})
total_intersections = len(intersection_details)
# Step 6: Plotting
# Plot 1: Only intersection points outside the circle
fig1, ax1 = plt.subplots()
plot_circle(ax1, points)
plot_intersections(ax1, [detail['point'] for detail in intersection_details])
ax1.set_aspect('equal')
ax1.set_xlim(-2, 2)
ax1.set_ylim(-2, 2)
ax1.set_title(f"Průsečíky mimo kružnici ({total_intersections})", fontsize=14)
# Plot 2: Infinite lines and their intersection points
fig2, ax2 = plt.subplots()
plot_circle(ax2, points)
plot_lines(ax2, [line['coefficients'] for line in lines], color='blue', linewidth=1, linestyle='-')
plot_intersections(ax2, [detail['point'] for detail in intersection_details])
# Annotate intersection points
for idx, detail in enumerate(intersection_details, start=1):
x, y = detail['point']
ax2.text(x, y, f"P{idx}", color='red', fontsize=9, ha='right', va='bottom')
ax2.set_aspect('equal')
ax2.set_xlim(-2, 2)
ax2.set_ylim(-2, 2)
ax2.set_title(f"Paralelní Primky a Průsečíky mimo kružnici ({total_intersections})", fontsize=14)
plt.show()
# Step 7: Output text information
if total_intersections == 0:
print("\nŽádné průsečíky mimo kružnici nebyly nalezeny.")
else:
print(f"\nCelkový počet průsečíků mimo kružnici: {total_intersections}\n")
print("Podrobnosti o průsečících:")
for idx, detail in enumerate(intersection_details, start=1):
x, y = detail['point']
line_a, line_b = detail['lines']
print(f"P{idx}: ({x:.6f}, {y:.6f})")
print(f" Vytváří je {line_a} a {line_b}.\n")
if __name__ == "__main__":
main()
Instrukce pro Použití Skriptu
-
Nainstalujte potřebné knihovny:
Ujistěte se, že máte nainstalované knihovny matplotlib. Pokud ne, můžete je nainstalovat pomocí pip:
pip install matplotlib
-
Spuštění Skriptu:
Uložte výše uvedený kód do souboru, například intersection_outside_circle.py, a spusťte ho pomocí Pythonu:
python intersection_outside_circle.py
-
Vstupní Data:
- Počet bodů na kružnici: Zadejte celé číslo větší nebo rovno 2.
- Definice úseček: Zadávejte úsečky jako páry indexů ve formátu
(číslo, číslo). Například (1,3) pro úsečku spojující první a třetí bod na kružnici.
- Dokončení zadávání úseček: Zadejte
done.
-
Výstupy:
- Graf 1: Zobrazuje pouze průsečíky mimo kružnici.
- Graf 2: Zobrazuje všechny poskytované primky a jejich průsečíky mimo kružnici.
- Textová Informace: Vypíše souřadnice každého průsečíku mimo kružnici spolu s informacemi o tom, které primky ho vytvářejí.
- Celkový Počet Průsečíků: Uvede celkový počet identifikovaných průsečíků mimo kružnici.
Příklad Použití
Pokud máte například 5 bodů na kružnici a definujete následující úsečky:
(1,3)
(2,4)
(1,4)
done
Skript vypočítá a zobrazí průsečíky těchto primek, které leží mimo kružnici, a poskytne vám jejich souřadnice a informace o tom, které úsečky vedly k jejich vytvoření.
Poznámky a Vylepšení
- Bezpečnost Vstupu: Skript obsahuje základní ověření vstupu, aby se předešlo chybám při zadávání úseků.
- Rozšiřitelnost: Skript lze snadno rozšířit pro další funkce, například ukládání výsledků do souboru nebo podporu různých tvarů kružnic.
- Grafické Úpravy: Grafy jsou nastaveny na rozsah -2 až 2 pro lepší vizualizaci, což můžete upravit dle potřeby.
Doufám, že tento skript splňuje vaše očekávání a pomůže vám při geometrických a matematických analýzách průsečíků mimo kružnici. Pokud máte jakékoli dotazy nebo potřebujete další úpravy, neváhejte se zeptat!