vytvor skript, který bude presne geometricky a matematicky zjišťovat průsečíky vne kruznice. skript na vstupu zada zadat počet bodu na kruznici a dvojice bodu na kruznici, které jsou usecky mezi dvěma body. zapis usecek bude ve formatu (číslo, číslo) na každý radek jedna usecka. program vygeneruje graf, v kterem bude kruznice rozdelena na uvedeny počet bodu, ale na misto usecek bude zakreslovat do dvou bodu primky. v garfu by mely byt viditelne všechny průsečíky, které mohou vzniknout vne kruznice a take bude uveden jejich celkovy soucet. jeden graf bude ukazovat pouze pruseciky, druhy graf bude ukazovat průsečíky i s primkami. skript dale vypise textove informace presne geometricke a matematicke polohy všech pruseciku mimo kruznici. u pruseciku bude take oznaceno, které puvodni usecky, vytvarejici primky a prusecik.
pridavam zdrojovy kod pro praci s průsečíky uvnitř kruznice, třeba nektre casti vyuzijes.
import matplotlib.pyplot as plt
from shapely.geometry import LineString, Point
import math
import itertools
def get_circle_points(N):
points = []
for i in range(N):
angle = 2 * math.pi * i / N
x = math.cos(angle)
y = math.sin(angle)
points.append((x, y))
return points
def input_line_segments():
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)
segments.append((idx1 - 1, idx2 - 1)) # Úprava na indexování od 0
except:
print("Neplatný vstup. Zadejte dvě celá čísla oddělená čárkou a uzavřená v závorkách, např. (1,3).")
return segments
# Najít všechny průsečíky
intersections = {}
for i, line1 in enumerate(lines):
for line2 in lines[i+1:]:
if line1['line'].intersects(line2['line']):
intersect_pt = line1['line'].intersection(line2['line'])
if isinstance(intersect_pt, Point):
x, y = intersect_pt.x, intersect_pt.y
# Přidat do slovníku, aby se předešlo duplicitám
key = (round(x, 8), round(y, 8))
intersections[key] = (x, y)
return intersections
new_segments = []
# Pro každou původní úsečku rozdělit pokud jsou průsečíky
for idx1, idx2 in segments:
x1, y1 = points[idx1]
x2, y2 = points[idx2]
line = LineString([(x1, y1), (x2, y2)])
# Najít všechny průsečíky na této úsečce
intersect_pts = []
for key, idx in intersection_indices.items():
xi, yi = intersections[key]
if line.distance(Point(xi, yi)) < 1e-8 and not ((xi == x1 and yi == y1) or (xi == x2 and yi == y2)):
# Vyhnout se koncovým bodům
intersect_pts.append((xi, yi, idx))
# Seřadit body podél úsečky
if intersect_pts:
pts = [(x1, y1, idx1)] + intersect_pts + [(x2, y2, idx2)]
# Vypočítat parametr t pro třídění
x0, y0 = x1, y1
dx, dy = x2 - x1, y2 - y1
def param_t(pt):
px, py = pt[0], pt[1]
return ((px - x0) * dx + (py - y0) * dy) / (dx**2 + dy**2)
pts.sort(key=param_t)
# Vytvořit úsečky mezi sousedními body
for i in range(len(pts) - 1):
idx_start = pts[i][2]
idx_end = pts[i+1][2]
new_segments.append((idx_start, idx_end))
else:
# Pokud není průsečík, zachovat původní úsečku
new_segments.append((idx1, idx2))
return new_segments, all_points
def main():
N = int(input("Zadejte počet bodů na kružnici: "))
points = get_circle_points(N)
segments = input_line_segments()
code
# Plot původních úseček
fig1, ax1 = plt.subplots()
plot_circle(ax1, points)
plot_segments(ax1, points, segments)
ax1.set_aspect('equal')
# Přidání textu s počtem úseček do nadpisu
total_original = len(segments)
ax1.set_title(f"Geometrický program\nCelkem je {total_original} useček.", fontsize=14)
# Výpočet průsečíků
intersections = compute_intersections(points, segments)
# Rozdělení úseček na průsečících
new_segments, all_points = subdivide_lines(points, segments, intersections)
# Odstranění duplicit
new_segments = list(set(tuple(sorted(seg)) for seg in new_segments))
# Výpis nových úseček
print("\nNové úsečky (mezi body):")
segment_data = []
for idx, (idx1, idx2) in enumerate(new_segments, start=1):
x1, y1 = all_points[idx1]
x2, y2 = all_points[idx2]
print(f"Úsečka {idx}: Bod {idx1 + 1} ({x1:.3f}, {y1:.3f}) do Bod {idx2 + 1} ({x2:.3f}, {y2:.3f})")
segment_data.append({
'segment_number': idx,
'start_index': idx1 + 1,
'end_index': idx2 + 1,
'start_point': (x1, y1),
'end_point': (x2, y2)
})
# Výpis celkového počtu nových úseček
total_segments = len(new_segments)
print(f"\nCelkový počet nových úseček: {total_segments}")
# Uložení do textové databáze (textový soubor)
with open('line_segments.txt', 'w') as f:
f.write("Segment_Number,Start_Index,End_Index,Start_X,Start_Y,End_X,End_Y\n")
for seg in segment_data:
f.write(f"{seg['segment_number']},{seg['start_index']},{seg['end_index']},"
f"{seg['start_point'][0]},{seg['start_point'][1]},"
f"{seg['end_point'][0]},{seg['end_point'][1]}\n")
print("\nÚsečky byly uloženy do souboru 'line_segments.txt'.")
# Plot nových úseček
fig2, ax2 = plt.subplots()
plot_circle(ax2, all_points)
# Číslování bodů, včetně průsečíků
for idx, (x, y) in enumerate(all_points):
ax2.plot(x, y, 'ko')
ax2.text(x * 1.05, y * 1.05, str(idx + 1), fontsize=8, ha='center', va='center')
for idx, (idx1, idx2) in enumerate(new_segments, start=1):
x1, y1 = all_points[idx1]
x2, y2 = all_points[idx2]
ax2.plot([x1, x2], [y1, y2], color='red')
# Označení úsečky na jejím středu
xm, ym = (x1 + x2) / 2, (y1 + y2) / 2
ax2.text(xm, ym, f"{idx}", color='blue', fontsize=8)
ax2.set_aspect('equal')
# Přidání textu s počtem úseček do nadpisu
ax2.set_title(f"Geometrický program\nCelkem je {total_segments} useček.", fontsize=14)
plt.show()
if name == "main":
main()
Certainly! Below is a Python script that fulfills all your requirements. This script allows you to:
Input:
Specify the number of points on a circle.
Define line segments between these points using pairs of point indices.
Processing:
Computes all intersection points between the defined line segments.
Determines which of these intersection points lie outside the circle.
Output:
Generates two plots:
Plot 1: Displays only the intersection points outside the circle.
Plot 2: Displays both the line segments and the intersection points outside the circle.
Provides a textual summary of all intersection points outside the circle, including their coordinates and the segments that form them.
Displays the total number of such intersection points.
The script leverages the matplotlib library for plotting and shapely for geometric computations. Ensure you have these libraries installed in your Python environment. You can install them using pip if you haven't already:
bash
pip install matplotlib shapely
Here's the complete script:
python
import matplotlib.pyplot as plt
from shapely.geometry import LineString, Point
import math
import itertools
def get_circle_points(N, radius=1):
"""
Calculate N points evenly distributed on a circle with 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) or not (1 <= idx2 <= N):
raise ValueError("Indexy musí být v rozsahu od 1 do N.")
if idx1 == idx2:
raise ValueError("Oba indexy nemohou být stejné.")
segments.append((idx1 - 1, idx2 - 1)) # 0-based indexing
except ValueError as ve:
print(f"Neplatný vstup: {ve}. Zadejte dvě celá čísla oddělená čárkou a uzavřená v závorkách, např. (1,3).")
return segments
def plot_circle_and_points(ax, points):
"""
Plot the circle and its defining points.
"""
circle = plt.Circle((0, 0), 1, 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_segments(ax, points, segments, color='blue', linewidth=1, linestyle='-'):
"""
Plot the line segments connecting the points.
"""
for idx1, idx2 in segments:
x1, y1 = points[idx1]
x2, y2 = points[idx2]
ax.plot([x1, x2], [y1, y2], color=color, linewidth=linewidth, linestyle=linestyle)
def compute_all_intersections(points, segments):
"""
Compute all intersection points between the line segments.
"""
lines = []
for idx, (idx1, idx2) in enumerate(segments):
x1, y1 = points[idx1]
x2, y2 = points[idx2]
line = LineString([(x1, y1), (x2, y2)])
lines.append({'indices': (idx1, idx2), 'line': line})
intersections = {}
intersection_details = {} # To store which segments intersect
for line1, line2 in itertools.combinations(lines, 2):
if line1['line'].intersects(line2['line']):
intersect_pt = line1['line'].intersection(line2['line'])
if isinstance(intersect_pt, Point):
x, y = intersect_pt.x, intersect_pt.y
# Round to avoid floating point issues
key = (round(x, 8), round(y, 8))
if key not in intersections:
intersections[key] = (x, y)
intersection_details[key] = [(line1['indices'], line2['indices'])]
else:
intersection_details[key].append((line1['indices'], line2['indices']))
return intersections, intersection_details
def filter_outside_intersections(intersections, threshold=1.0):
"""
Filter intersection points that lie outside the circle with given threshold radius.
"""
outside = {}
for key, (x, y) in intersections.items():
distance = math.hypot(x, y)
if distance > threshold:
outside[key] = (x, y)
return outside
def plot_intersections_only(ax, outside_intersections):
"""
Plot only the intersection points outside the circle.
"""
for (x, y) in outside_intersections.values():
ax.plot(x, y, 'ro') # Red dots for intersections
ax.set_aspect('equal')
def plot_intersections_with_segments(ax, points, segments, outside_intersections):
"""
Plot the segments and the intersection points outside the circle.
"""
plot_segments(ax, points, segments, color='blue', linewidth=1, linestyle='-')
for (x, y) in outside_intersections.values():
ax.plot(x, y, 'ro') # Red dots for intersections
ax.set_aspect('equal')
def main():
# 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. Prosím zadejte celé číslo.")
return
# Step 2: Generate circle points
points = get_circle_points(N)
# Step 3: Input line segments
segments = input_line_segments(N)
if not segments:
print("Nebyla zadána žádná úsečka.")
return
# Step 4: Compute all intersections
intersections, intersection_details = compute_all_intersections(points, segments)
# Step 5: Filter intersections outside the circle
outside_intersections = filter_outside_intersections(intersections, threshold=1.0)
# Step 6: Plotting
# Plot 1: Only intersection points outside the circle
fig1, ax1 = plt.subplots()
plot_circle_and_points(ax1, points)
plot_intersections_only(ax1, outside_intersections)
ax1.set_title(f"Průsečíky mimo kružnici\nCelkem: {len(outside_intersections)}", fontsize=14)
ax1.set_xlim(-1.5, 1.5)
ax1.set_ylim(-1.5, 1.5)
# Plot 2: Segments with intersection points outside the circle
fig2, ax2 = plt.subplots()
plot_circle_and_points(ax2, points)
plot_intersections_with_segments(ax2, points, segments, outside_intersections)
ax2.set_title(f"Průsečíky a úsečky\nPrůsečíky mimo kružnici: {len(outside_intersections)}", fontsize=14)
ax2.set_xlim(-1.5, 1.5)
ax2.set_ylim(-1.5, 1.5)
# Annotate intersection points with labels
for idx, ((x, y), (pt_x, pt_y)) in enumerate(outside_intersections.items(), start=1):
ax2.text(pt_x, pt_y, f"P{idx}", color='red', fontsize=9)
# Step 7: Display plots
plt.show()
# Step 8: Textual output
if outside_intersections:
print(f"\nCelkový počet průsečíků mimo kružnici: {len(outside_intersections)}\n")
for idx, (key, (x, y)) in enumerate(outside_intersections.items(), start=1):
print(f"Průsečík P{idx}: ({x:.6f}, {y:.6f})")
print(" Tvoří se úsečkami:")
for pair in intersection_details[key]:
seg1, seg2 = pair
print(f" Úsečka {seg1[0]+1}-{seg1[1]+1} a Úsečka {seg2[0]+1}-{seg2[1]+1}")
print()
else:
print("\nŽádné průsečíky mimo kružnici nebyly nalezeny.")
if __name__ == "__main__":
main()
Jak Skript Funguje
Vstup:
Počet bodů na kružnici (N): Skript nejprve požádá uživatele o zadání počtu bodů, které budou rovnoměrně rozmístěny na kružnici.
Definice úseček: Uživatel zadá úsečky jako dvojice indexů bodů ve formátu (číslo, číslo), např. (1,3). Zadejte done pro dokončení zadávání.
Výpočet:
Generování bodů: Body jsou vypočítány tak, aby byly rovnoměrně rozloženy na kružnici jednotkového poloměru.
Výpočet průsečíků: Skript vypočítá všechny možné průsečíky mezi zadanými úsečkami.
Filtrace průsečíků mimo kružnici: Získané průsečiky jsou filtrovány tak, aby zůstaly pouze ty, které leží mimo kružnici (vzdálenost od středu větší než 1).
Výstup:
Graf 1: Zobrazuje pouze průsečíky, které leží mimo kružnici.
Graf 2: Zobrazuje všechny zadané úsečky spolu s průsečíky, které leží mimo kružnici.
Textový Přehled: Vypíše souřadnice všech průsečíků mimo kružnici a uvádí, které úsečky je tvořily.
Ukázka Použití
Předpokládejme, že chceme mít na kružnici 6 bodů a definujeme několik úseček mezi nimi.
Vstup:
code
Zadejte počet bodů na kružnici: 6
Zadejte úsečky jako dvojice indexů bodů ve formátu (cislo, cislo).
Například: (1,3)
Zadejte 'done' pro dokončení.
Zadejte úsečku: (1,4)
Zadejte úsečku: (2,5)
Zadejte úsečku: (3,6)
Zadejte úsečku: done
Výstup:
Graf 1: Zobrazí kružnici s body 1 až 6 a pouze průsečíky mimo kružnici, pokud existují.
Graf 2: Zobrazí kružnici, všechny zadané úsečky a průsečíky mimo kružnici, označené jako P1, P2, atd.
Textový Přehled:
code
Celkový počet průsečíků mimo kružnici: X
Průsečík P1: (x1, y1)
Tvoří se úsečkami:
Úsečka A-B a Úsečka C-D
Průsečík P2: (x2, y2)
Tvoří se úsečkami:
Úsečka E-F a Úsečka G-H
Kde X je počet průsečíků mimo kružnici, a A-B, C-D atd. jsou indexy úseček, které tvoří daný průsečík.
Poznámky
Skript kontroluje, zda jsou zadané indexy platné (tj. v rozsahu od 1 do N) a zda nejsou úsečky definovány mezi stejným bodem.
Průsečíky na samotné kružnici (vzdálenost rovna 1) nejsou zahrnuty do výsledků.
Skript může být dále rozšířen o ukládání grafů nebo dalších analytických funkcí podle potřeby.
Doufám, že tento skript splní vaše požadavky! Pokud máte jakékoliv další otázky nebo potřebujete úpravy, neváhejte se zeptat.