Программа решения системы двух нелинейных уравнений графическим методом

prarabacha

Новичок
Пользователь
Окт 27, 2021
15
1
3
Здравствуйте, не мог бы мне кто-то объяснить почему выдаёт ошибку, что модуль не назван. был бы благодарен.
Screenshot_1.png
Собственно, программа не запускается. Также, был бы признателен на указание ошибок и какой-то правки в самом коде. Сам код:


Код:
import collections
import scipy.spatial as spatial
import scipy.spatial.distance as dist
import scipy.cluster.hierarchy as hier
import matplotlib.pyplot as plt
from numpy import arange, meshgrid, sin, arcsin, cos, arccos, tan, arctan, abs, log, sqrt, roots, argwhere, diff, sign
import numpy as np
from math import pi, e


def main_prog():
    first_eq = input("Enter the first nonlinear level in the form F(x, y) = 0: ")
    second_eq = input ("Enter the second nonlinear equation in the form F(x, y) = 0: ")

    def change(equation):
        list = []
        for symbol in equation:
            if symbol == ' ':
                continue
            elif symbol == '^':
                list.append("**")
                continue
            elif symbol.isalpha():
                symbol = symbol.lower()
            elif symbol == '=':
                break
            list.append(symbol)
        return ''.join(list)

    first_eq = change(first_eq)
    second_eq = change(second_eq)

    if second_eq == first_eq:
        print("The equations are the same, the points of intersection are many.")
        return False

    def template_for_graphic():
        fig, ax = plt.subplots()

        # Встановлення нижнього та лівого обложки як осі x і y системи координат.
        ax.spines['bottom'].set_position('zero')
        ax.spines['left'].set_position('zero')

        # Видаліть верхні та праві обложки.
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)

        # Створіть мітки: «x» та «y», що розміщені в кінці осей.
        ax.set_xlabel('x', size=14, labelpad=15)
        ax.set_ylabel('y', size=14, labelpad=15, rotation=0)
        ax.xaxis.set_label_coords(1.03, 0.512)
        ax.yaxis.set_label_coords(0.5, 1.02)

        # Намалюйте лінії сітки.
        ax.grid(which='major', color='grey', linewidth=1, linestyle='-', alpha=0.2)
        ax.grid(which='minor', color='grey', linewidth=1, linestyle='-', alpha=0.2)

        # Намалюйте стрілки.
        ax.plot((1), (0), linestyle="", marker=">", markersize=4, color="k",
                transform=ax.get_yaxis_transform(), clip_on=False)
        ax.plot((0), (1), linestyle="", marker="^", markersize=4, color="k",
                transform=ax.get_xaxis_transform(), clip_on=False)

    template_for_graphic()


    def sorting_float(s):
        try:
            float(s)
            return True
        except ValueError:
            return False

    def sorting_int(s):
        try:
            float(s)
            return True
        except ValueError:
            return False

    while True:
        min = input("Enter the minimum possible value to search for roots: ")
        if sorting_float(min):
            if float(min) > 100 or float(min) < -100:
                print("You have entered a value out of range, please, try again!!!")
                continue
            min = float(min)
        else:
            print("You made a mistake while entering the number, please, try again!!!")
            continue
        break


    while True:
        max = input("Enter the maximum possible value to search for roots: ")
        if sorting_float(max):
            if  float(min) > 100 or float(min) < -100:
                print("You have entered a value outside the range, please, try again!!!")
                continue
            max = float(max)
            if max == min or max < min:
                print("The maximum value is the same as the minimum or less than the minimum, please, try again!!!")
                continue
        else:
            print("You made a mistake while entering the number, please, try again!!!")
            continue
        break

    while True:
        round_n = input("Enter the accuracy (1 to 3, where 1 is the minimum accuracy and 3 is the maximum): ")
        if sorting_int(round_n):
            if int(round_n) > 3 or int(round_n) < 1 :
                print("You have entered an invalid value, please, try again!!!")
                continue
            round_n = int(round_n)
        else:
            print("You made a mistake while entering the number, please, try again!!!")
            continue
        break



    def intersection(points1, points2, eps):
        tree = spatial.KDTree(points1)
        distances, indices = tree.query(points2, k=1, distance_upper_bound=eps)
        intersection_points = tree.data[indices[np.isfinite(distances)]]
        return intersection_points

    def cluster(points, cluster_size):
        dists = dist.pdist(points, metric = 'sqeuclidean')
        linkage_matrix = hier.linkage(dists, 'average')
        groups = hier.fcluster(linkage_matrix, cluster_size, criterion = 'distance')
        return np.array([points[cluster].mean(axis=0)
                         for cluster in clusterlists(groups)])

    def contour_points(contour, steps = 1):
        return np.row_stack([path.interpolated(steps).vertices
                             for linecol in contour.collections
                             for path in linecol.get_paths()])

    def clusterlists(T):
        '''
        T = [2, 1, 1, 1, 2, 2, 2, 2, 2, 1]
        Returns [[0, 4, 5, 6, 7, 8], [1, 2, 3, 9]]
        '''
        groups = collections.defaultdict(list)
        for i, elt in enumerate(T):
            groups[elt].append(i)
        return sorted(groups.values(), key = len, reverse = True)

    # Кожна точка перетину повинна знаходитися в межах eps від точки на іншій контурному шляху.
    eps = 1

    # cluster разом точки перетину так, щоб вихідні точки в кожному місці.
    # cluster має cophenetic_distance < cluster_size.
    cluster_size = 1

    plus_app = max
    minus_app = min
    if min < 0 and max > 0:
        delta = abs(round((0.009 * max), 6))
    else:
        thing_for_delta = abs(abs(max) - abs(min))
        delta = abs((0.009 * thing_for_delta))

    def build(first_eq, second_eq, delta, minus_app, plus_app):
        try:
            x, y = meshgrid(
                arange(minus_app, plus_app, delta),
                arange(minus_app, plus_app, delta)
            )
            str1 = eval(first_eq)

            contour1 = plt.contour(
                x, y,
                str1,
                [0]
            )

            str1 = []

            x, y = meshgrid(
                arange(minus_app, plus_app, delta),
                arange(minus_app, plus_app, delta)
            )
            str_0 = eval(second_eq)

            contour2 = plt.contour(
                x, y,
                str_0,
                [0]
            )

            str_0 = []

            points1 = contour_points(contour1)
            points2 = contour_points(contour2)

            intersection_points = intersection(points1, points2, eps)
            try:
                intersection_points = cluster(intersection_points, cluster_size)
            except ValueError:
                print("No solutions found!!!")
                return False
            plt.scatter(intersection_points[:, 0], intersection_points[:, 1], s=20)
            if intersection_points.size == 0:
                print("No solutions found!!!")
            elif intersection_points.size > 100:
                print("There are many points of intersection.")
            else:
                print("The following intersection points were found: ")
                print(intersection_points)
            plt.show()
            return intersection_points
        except NameError and SyntaxError:
            print("You made a mistake while writing the equations, please, try again!!!")
            main_prog()

    intersection_points = build(first_eq, second_eq, delta, minus_app, plus_app)

    def check(intersection_points, first_eq, second_eq):
        list = []
        try:
            for z in range(0, len(intersection_points)):
                list_empty = []
                x = round(intersection_points[z][0], 4)
                y = round(intersection_points[z][1], 4)
                first_eq_end = eval(first_eq)
                second_eq_end = eval(second_eq)
                list_empty.append(first_eq_end)
                list_empty.append(second_eq_end)
                list.append(list_empty)
            print("Errors:", list)
        except NameError or SyntaxError or ValueError:
            pass

    check(intersection_points, first_eq, second_eq)

print("Program for connecting a system of two nonlinear equations graphically.")
print("Calculator for solving a system of two nonlinear equations by the graphical method.")
print("The calculator can find solutions only if they are in the range from -100 to 100.")

while True:
    main_prog()
    print('Do you want to continue the program? (Yes - any key / no - no).')
    prog = input()
    if prog == 'no':
        break
 
Последнее редактирование:

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 672
478
83
вам нужно установить модуль scipy, в командной строке или в терминале вашей IDE пишите pip install scipy
 

weamagic

Пользователь
Пользователь
Июл 11, 2020
149
13
18
Если это PyCharm, то проверь настройки использования библиотек. У него есть два режима: использовать библиотеки, установленные в системе (это то, что делается через окно cmd) или загружать библиотеки непосредственно в проект (устанавливается в настройках среды, заливается в папку venv проекта).
В случае активации второго режима, надо навести курсор на красную волнистую линию и в появившемся окне нажать "Install package"
 
  • Мне нравится
Реакции: Student

Форум IT Специалистов