Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions 1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# +
import numpy as np
import matplotlib.pyplot as plt

# Параметры уравнения
alpha = 350.0 # 1/с
omega = 614.4 # рад/с
A = -15.75 # коэф. при cos
B = -8.17 # коэф. при sin
i_pr_val = -43.75 # принуждённая составляющая

tau = 1 / alpha # ≈ 0.002857 с
t_max = 0.018 # 18 мс (> 6τ)

# Время
t_before = np.linspace(-0.005, 0, 100)
t_after = np.linspace(0, t_max, 3000)
t_full = np.concatenate([t_before, t_after])

# Принуждённая составляющая (постоянна)
i_pr = np.full_like(t_full, i_pr_val)

# Свободная составляющая
i_sv_before = np.zeros_like(t_before) # до коммутации нет переходного процесса
i_sv_after = np.exp(-alpha * t_after) * (A * np.cos(omega * t_after) + B * np.sin(omega * t_after))
i_sv_full = np.concatenate([i_sv_before, i_sv_after])

# Полный ток
i_full = i_pr + i_sv_full

# Проверка значений
i0_plus = i_full[len(t_before)] # первое значение при t >= 0
print(f"i(0+) = {i0_plus:.3f} А (ожидается: {A + i_pr_val:.3f} = {-15.75 - 43.75:.3f} А)")
print(f"i(∞) = {i_pr_val} А")
print(f"i_sv(0+) = {i_sv_full[len(t_before)]:.3f} А (ожидается: {A} А)")

# Построение
plt.figure(figsize=(13, 7))

plt.plot(t_full, i_full, 'b-', linewidth=2.5, label=r'Полный ток $i(t) = i_{\text{пр}} + i_{\text{св}}$')
plt.plot(t_full, i_pr, 'r--', linewidth=1.8, label=rf'Принуждённая: $i_{{\text{{пр}}}} = {i_pr_val}\ \text{{А}}$')
plt.plot(t_full, i_sv_full, 'g-.', linewidth=2.0, label=r'Свободная составляющая $i_{\text{св}}(t)$')

# Вертикальные линии
plt.axvline(x=0, color='k', linestyle=':', linewidth=1.5, label='Коммутация ($t = 0$)')
plt.axvline(x=3*tau, color='m', linestyle=':', linewidth=1.2, label=rf'$t = 3\tau \approx {3*tau*1000:.1f}\ \text{{мс}}$')

# Дополнительно: отметим начальное значение
plt.axhline(y=i0_plus, color='orange', linestyle=':', linewidth=1, alpha=0.7)

# Оформление
plt.axhline(y=0, color='gray', linewidth=0.6, alpha=0.5)
plt.xlabel('Время, с', fontsize=12)
plt.ylabel('Ток $i$, А', fontsize=12)
plt.title(
r'Переходный процесс: $i(t) = (-15.75 \cos 614.4t - 8.17 \sin 614.4t)\, e^{-350t} - 43.75$',
fontsize=13, pad=15
)
plt.grid(True, alpha=0.3, linestyle='--')
plt.legend(fontsize=10)
plt.xlim(-0.005, t_max)
plt.ylim(-75, 10) # учитываем отрицательный пик ~ -59.5 А

# Аннотации
plt.text(0.0005, -40, rf'$i(0_+) = {i0_plus:.1f}\ \text{{А}}$', color='b', fontsize=10)
plt.text(0.0005, -62, r'$i_{\text{св}}(0_+) = -15.75\ \text{А}$', color='g', fontsize=10)
plt.text(0.0005, -48, rf'$i_{{\text{{пр}}}} = {i_pr_val}\ \text{{А}}$', color='r', fontsize=10)
plt.text(3*tau + 0.0003, -72, '3τ', color='m', fontsize=9, rotation=90)

# Подпись до коммутации
plt.text(-0.0045, -65, 'До коммутации:\n$i = 0$, $i_{\\text{св}} = 0$', fontsize=9, color='k')

plt.tight_layout()
plt.show()
# -




20 changes: 20 additions & 0 deletions Installation_guide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Установка и настрока Jupiter Lab на Windows (проверено на Windows 11 Home) для дисциплины Алгоритмы и структуры данных
## 1. Скачиваем Anaconda с официального сайта: https://www.anaconda.com/download.
## 2. Заходим в репозиторий dsa на гитхаб https://github.com/askras/dsa и делаем форк его к себе в аккаунт:
![Компьютер](img/1.png)
## 3. В своем аккаунте выбираем репозиторий dsa и копируем ключ SSH:
![Компьютер](img/2.png)
## 4. В командной строке переходим в папку, куда хотим склонировать репозиторий и прописываем команду **git clone “вставляем наш ключ”**.
## 5. Проверяем установлен ли питон командой **python –version**, должны увидеть следующий результат:
![Компьютер](img/3.png)
## (главное чтобы была написана версия питона, цифры могут отличаться, но версия должна быть не ниже 3.13, если цифр нет или текст отличается, то нужно установить питон).
## 6. Заходим в WindowsPowershell и переходим в папку с нашим репозиторием на ПК командой **cd “путь к папке dsa”**.
## 7. Прописываем команду **python -m venv labvenv**, должна появиться папка labvenv в папке dsa:
![Компьютер](img/4.png)
## 8. Переходим в папку labsvenv командой **cd labsvenv** и прописываем команду **.\Scripts\Activate.ps1**.
## 9. Возвращаемся в папку dsa командой **cd “путь к папке dsa”** и прописываем команду **pip install -r requirements.txt**, должно начаться скачивание файлов.
## 10. Пишем команду **jupyter lab** и в браузере должен открыться jupyter lab с нашим репозиторием dsa и возможностью запускать файлы питона:
![Компьютер](img/5.png)
## Чтобы отключить jupyter lab закройте вкладку браузера, в Powershell нажмите Ctrl+C и пропишите команду **deactivate**.

## Авторы: @telerink и @risullkin
Binary file added img/1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/5.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
168 changes: 168 additions & 0 deletions labs/lab_01/Zadanie1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# +
# 1
import functools
import timeit
import typing

def get_usage_time(
*, number: int = 1, setup: str = 'pass', ndigits: int = 3
) -> typing.Callable:
def decorator(func: typing.Callable) -> typing.Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs) -> float:
usage_time = timeit.timeit(
lambda: func(*args, **kwargs),
setup=setup,
number=number,
)
return round(usage_time / number, ndigits)

return wrapper

return decorator


# +
# 2
import random

N = 6

def vector_generator(n):
vec = [random.randint(1, 100*N) for i in range(n)]
return vec
#1.2
def summa_func(n):
vec = vector_generator(n)
summ = 0
for num in vec:
summ += num
return summ
#1.3
def proizvedenie_func(n):
vec = vector_generator(n)
proizv = 1
for num in vec:
proizv *= num
return proizv
#1.5
def maximum_func(n):
vec = vector_generator(n)
maxi = 0
for num in vec:
if num >= maxi:
maxi = num
return maxi
#1.7
# def srednee_arifm_func(vec):
# vec = vector_generator(n)
# summ = 0
# lenn = 0
# for num in vec:
# summ += num
# lenn += 1
# return summ/lenn
#1.8
def srednee_garm_func(n):
vec = vector_generator(n)
summ = 0
lenn = 0
for num in vec:
summ += num
lenn += 1
return lenn/summ


# +
#3
import matplotlib.pyplot as plt

N = 6

def five_iteration_summa(n):
time_of_summa = []
summa_time = get_usage_time(ndigits=5)(summa_func)
for i in range(5):
time_of_summa.append(summa_time(n))
average_time_summa = sum(time_of_summa)/5
return average_time_summa

def five_iteration_proizvedenie(n):
time_of_proizvedenie = []
proizvedenie_time = get_usage_time(ndigits=5)(proizvedenie_func)
for i in range(5):
time_of_proizvedenie.append(proizvedenie_time(n))
average_time_proizvedenie = sum(time_of_proizvedenie)/5
return average_time_proizvedenie

def five_iteration_maximum(n):
time_of_maximum = []
maximum_time = get_usage_time(ndigits=5)(maximum_func)
for i in range(5):
time_of_maximum.append(maximum_time(n))
average_time_maximum = sum(time_of_maximum)/5
return average_time_maximum

def five_iteration_srednee(n):
time_of_srednee = []
srednee_time = get_usage_time(ndigits=5)(srednee_garm_func)
for i in range(5):
time_of_srednee.append(srednee_time(n))
average_time_srednee = sum(time_of_srednee)/5
return average_time_srednee

# %matplotlib inline

items = range(1, 10**5*N+1, 1000*N)

times_summa = []
times_proizvedenie = []
times_maximum = []
times_srednee = []

j = 0

for i in items:
times_summa.append(five_iteration_summa(i))
times_proizvedenie.append(five_iteration_proizvedenie(i))
times_maximum.append(five_iteration_maximum(i))
times_srednee.append(five_iteration_srednee(i))
if i > 1000:
print('Среднее время произведения для', i, 'элементов:', times_proizvedenie[j])
j += 1

#Summa
plt.figure(figsize=(10, 6))
plt.plot(items, times_summa)
plt.title('График суммы элементов')
plt.xlabel('Запуски программы')
plt.ylabel('Время, сек')
plt.grid(True)

#Proizvedenie
plt.figure(figsize=(10, 6))
plt.plot(items, times_proizvedenie)
plt.title('График произведения элементов')
plt.xlabel('Запуски программы')
plt.ylabel('Время, сек')
plt.grid(True)

#Maximum
plt.figure(figsize=(10, 6))
plt.plot(items, times_maximum)
plt.title('График максимума из элементов')
plt.xlabel('Запуски программы')
plt.ylabel('Время, сек')
plt.grid(True)

#Srednee
plt.figure(figsize=(10, 6))
plt.plot(items, times_srednee)
plt.title('График среднего гармонического элементов')
plt.xlabel('Запуски программы')
plt.ylabel('Время, сек')
plt.grid(True)
# -

83 changes: 83 additions & 0 deletions labs/lab_01/Zadanie2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# +
# 1
import functools
import timeit
import typing

def get_usage_time(
*, number: int = 1, setup: str = 'pass', ndigits: int = 3
) -> typing.Callable:
def decorator(func: typing.Callable) -> typing.Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs) -> float:
usage_time = timeit.timeit(
lambda: func(*args, **kwargs),
setup=setup,
number=number,
)
return round(usage_time / number, ndigits)

return wrapper

return decorator


# +
# 2
import random

N = 6

def matrix_generator(n):
matrix = []
for i in range(n):
line = [random.randint(1, 100*N) for j in range(n)]
matrix.append(line)
return matrix

def matrix_proizv(n):
a = matrix_generator(n)
b = matrix_generator(n)
c = [[] for i in range(n)]
for i in range(n):
for j in range(n):
element = 0
for k in range(n):
element += a[i][k] * b[k][j]
c[i].append(element)
return c


# +
# 3
import matplotlib.pyplot as plt

N = 6

def five_iteration_matrix(n):
time_of_matrix = []
matrix_time = get_usage_time(ndigits=5)(matrix_proizv)
for i in range(5):
time_of_matrix.append(matrix_time(n))
average_time_matrix = sum(time_of_matrix)/5
return average_time_matrix

# %matplotlib inline

items = range(1, 10**2*N+1, 10)
times_matrix = []
j = 0
for i in items:
times_matrix.append(five_iteration_matrix(i))
print('Среднее время произведения матриц для', i, 'порядка матрицы', times_matrix[j])
j += 1

plt.figure(figsize=(10, 6))
plt.plot(items, times_matrix)
plt.title('График для произведения матриц')
plt.xlabel('Порядок матрицы')
plt.ylabel('Время, сек')
plt.grid(True)
# -


Loading