добавить сюда расчёт с помощью mpi. каждый процесс здесь обрабатывает свои отрезки по…
- User
добавить сюда расчёт с помощью mpi. каждый процесс здесь обрабатывает свои отрезки по порядку по уже заданному алгоритму, после чего собираются с помощью Gather. результат ДОБАВЛЯЕТСЯ на график, где отобразить вниз оси абсцисс, посчитанное напрямую так и остаётся на графике
import numpy as np import matplotlib.pyplot as plt
def create_jacobi_matrix(n, c1, c2, b): c = np.array([c1 if i % 2 == 0 else c2 for i in range(n)]) b = np.full(n-1, b) return np.diag(c) + np.diag(b, k=1) + np.diag(b, k=-1)
def calculate_sturm_count(diagonal, off_diagonal, x): n = len(diagonal) p0 = 1.0 p1 = diagonal[0] - x if np.isclose(p1, 0): p1 = 1e-10 count = 0 if p1 < 0: count += 1 for i in range(1, n): p2 = (diagonal[i] - x) * p1 - off_diagonal[i-1]**2 * p0 if np.isclose(p2, 0): p2 = 1e-10 if p1 * p2 < 0: count += 1 p0, p1 = p1, p2 return count
Параметры
n = 100 c1 = 12 c2 = 7 b = 15
Генерация матрицы Якоби
jacobi_matrix = create_jacobi_matrix(n, c1, c2, b) diagonal = np.diag(jacobi_matrix) off_diagonal = np.diag(jacobi_matrix, k=1)
Получение собственных значений
eigenvalues, _ = np.linalg.eig(jacobi_matrix) interval_min, interval_max = eigenvalues.min(), eigenvalues.max()
Создание точек для интервала
num_points = 20 # Количество точек step = (interval_max - interval_min) / num_points x_points = np.linspace(interval_min - step, interval_max + step, num_points + 2)
Подсчёт числа собственных значений в каждом отрезке
eigenvalue_counts = []
for x in x_points: eigenvalue_counts.append(calculate_sturm_count(diagonal, off_diagonal, x))
Вычисление различий между соседними значениями
count_differences = np.diff(eigenvalue_counts)
Построение гистограммы
plt.bar(x_points[:-1], count_differences, width=(x_points[1]-x_points[0]), align='edge') plt.xlabel('Отрезки') plt.ylabel('Изменение числа собственных значений') plt.title('Количество собственных значений в каждом отрезке')
Установка меток на оси абсцисс
plt.xticks(ticks=x_points[:-1], labels=[f'{x:.2f}' for x in x_points[:-1]], rotation=45, ha="right") plt.tight_layout() # Чтобы текст графика не накладывался plt.show()
eigenvalues.sort() print("Собственные значения:\n", eigenvalues)
- Assistant
- User
Traceback (most recent call last): File "C:\Users\home\Desktop\Simple\mpi2.py", line 90, in plt.bar(x_points[:-1], count_differences, width=(x_points[1]-x_points[0]), align='edge') File "C:\Users\home\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\pyplot.py", line 2739, in bar return gca().bar( ^^^^^^^^^^ File "C:\Users\home\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib_init_.py", line 1478, in inner return func(ax, *map(sanitize_sequence, args), **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\home\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\axes_axes.py", line 2457, in bar x, height, width, y, linewidth, hatch = np.broadcast_arrays( ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\home\AppData\Local\Programs\Python\Python312\Lib\site-packages\numpy\lib\stride_tricks.py", line 540, in broadcast_arrays shape = _broadcast_shape(*args) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\home\AppData\Local\Programs\Python\Python312\Lib\site-packages\numpy\lib\stride_tricks.py", line 422, in _broadcast_shape b = np.broadcast(*args[:32]) ^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (21,) and arg 1 with shape (20,).
- Assistant
Ошибка сообщает о несовпадении форм массивов, которые вы передаете функции построения графика
plt.bar(). Вероятно, это связано с тем, что длина массиваx_points[:-1]не совпадает с длиной массива . Давайте разберемся с этой проблемой и исправим код. - User
Traceback (most recent call last): File "C:\Users\home\Desktop\Simple\mpi2.py", line 92, in plt.bar(x_points[:-1], count_differences, width=(x_points[1]-x_points[0]), align='edge') File "C:\Users\home\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\pyplot.py", line 2739, in bar return gca().bar( ^^^^^^^^^^ File "C:\Users\home\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib_init_.py", line 1478, in inner return func(ax, *map(sanitize_sequence, args), **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\home\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\axes_axes.py", line 2457, in bar x, height, width, y, linewidth, hatch = np.broadcast_arrays( ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\home\AppData\Local\Programs\Python\Python312\Lib\site-packages\numpy\lib\stride_tricks.py", line 540, in broadcast_arrays shape = _broadcast_shape(*args) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\home\AppData\Local\Programs\Python\Python312\Lib\site-packages\numpy\lib\stride_tricks.py", line 422, in _broadcast_shape b = np.broadcast(*args[:32]) ^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (21,) and arg 1 with shape (17,).
- Assistant
- User
выведи весь код с исправлениями
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.