Matplotlib, python, cum de a găsi punctele în care o linie taie axa x

0

Problema

Am fost de lucru pe unele cod pentru a rezolva o ecuație de gradul doi și pe un grafic, vreau pentru a obține un punct în punctele unde linia taie axa x, și coordonatele punctelor afișat mai jos le. Aceasta este ceea ce face codul acum. Aceasta este ceea ce vreau să fac.

Codul este după cum urmează:

import matplotlib

matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
import math


def int_input(prompt):
    while True:
        try:
            variable_name = int(input(prompt))
            return variable_name
        except ValueError:
            print("Please enter a whole number (in digits)")


def float_input(prompt):
    while True:
        try:
            variable_name = float(input(prompt))
            return variable_name
        except ValueError:
            print("Please enter a numeric value (in digits)")


def yes_input(prompt):
    while True:
        variable_name = input(prompt).lower()
        if variable_name in ["y", "yes"]:
            return "yes"
        elif variable_name in ["n", "no"]:
            return "no"
        else:
            print("""Please enter either "y" or "n". """)


print("Quadratic Solver")

while True:

    print("Input below the values of a, b and c from an equation that is of the form : ax² + bx + c = 0")
    a = float_input('a: ')

    b = float_input('b: ')

    c = float_input('c: ')

    # calculate the discriminant
    d = (b ** 2) - (4 * a * c)

    # find two solutions
    try:
        solution1 = (-b - math.sqrt(d)) / (2 * a)
    except ValueError:
        solution1 = "none"

    try:
        solution2 = (-b + math.sqrt(d)) / (2 * a)
    except ValueError:
        solution2 = "none"

    if solution1 == solution2:
        if solution1 == "none":
            print("There are no solutions.")
        else:
            print("There is one solution: x = {0}".format(solution1))

    elif solution1 != solution2:
        print('There are two solutions, x can be either {0} or {1}'.format(solution1, solution2))

    graph = yes_input("Do you want to plot that on a graph? (y/n):  ")
    if graph == "yes":
        x = np.linspace(-6, 6, 50)

        fig = plt.figure(figsize=(7, 4))

        y4 = a * x ** 2 + b * x + c
        plt.plot(x, y4, 'g:', label='Degree 2')

        # Add features to our figure
        plt.legend()
        plt.grid(True, linestyle=':')
        plt.xlim([-6, 6])
        plt.ylim([-4, 4])

        plt.title(f'A graph of {a}x² + {b}x + {c} = 0')
        plt.xlabel('x-axis')
        plt.ylabel('y-axis')
        plt.get_current_fig_manager().window.wm_geometry("+0+0")
        fig.canvas.manager.window.attributes('-topmost', 1)
        # Show plot
        plt.show()
    new_question = yes_input('New question? (y/n): ')
    if new_question == "no":
        break

Eu sunt pe sistemul de OPERARE windows și sunt, folosind IntelliJ IDEA de a edita codul python.

matplotlib python
2021-11-23 22:42:07
1

Cel mai bun răspuns

1

Pentru a adăuga puncte la graficul de o ecuație de gradul doi, puteți utiliza plt.complot funcția cu cercuri markeri, și de a folosi plt.text pentru a imprima coordonatele de puncte.

Avem o soluție bazată pe cod. Nu e cel mai curat, dar este ușor de înțeles (linia 86-96).

import matplotlib

matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
import math

def int_input(prompt):
    while True:
        try:
            variable_name = int(input(prompt))
            return variable_name
        except ValueError:
            print("Please enter a whole number (in digits)")


def float_input(prompt):
    while True:
        try:
            variable_name = float(input(prompt))
            return variable_name
        except ValueError:
            print("Please enter a numeric value (in digits)")


def yes_input(prompt):
    while True:
        variable_name = input(prompt).lower()
        if variable_name in ["y", "yes"]:
            return "yes"
        elif variable_name in ["n", "no"]:
            return "no"
        else:
            print("""Please enter either "y" or "n". """)


print("Quadratic Solver")

while True:

    print("Input below the values of a, b and c from an equation that is of the form : ax² + bx + c = 0")
    a = float_input('a: ')

    b = float_input('b: ')

    c = float_input('c: ')

    # calculate the discriminant
    d = (b ** 2) - (4 * a * c)

    # find two solutions
    try:
        solution1 = (-b - math.sqrt(d)) / (2 * a)
    except ValueError:
        solution1 = "none"

    try:
        solution2 = (-b + math.sqrt(d)) / (2 * a)
    except ValueError:
        solution2 = "none"

    if solution1 == solution2:
        if solution1 == "none":
            print("There are no solutions.")
        else:
            print("There is one solution: x = {0}".format(solution1))

    elif solution1 != solution2:
        print('There are two solutions, x can be either {0} or {1}'.format(solution1, solution2))

    graph = yes_input("Do you want to plot that on a graph? (y/n):  ")
    if graph == "yes":
        x = np.linspace(-6, 6, 50)

        fig = plt.figure(figsize=(7, 4))

        y4 = a * x ** 2 + b * x + c
        plt.plot(x, y4, 'g:', label='Degree 2')

        # Add features to our figure
        plt.legend()
        plt.grid(True, linestyle=':')
        plt.xlim([-6, 6])
        plt.ylim([-4, 4])

        # Add dots
        offset = 0.3

        if solution1 == solution2:
            if solution1 != "none":
                plt.plot(solution1, 0 , marker="o", markersize=10, color="black", linestyle="None")
                plt.text(solution1, 0-offset, f'({solution1}, {0})', ha='center', va='center')
        elif solution1 != solution2:
            plt.plot([solution1, solution2], [0, 0], marker="o", markersize=10, color="black", linestyle="None")
            plt.text(solution1, 0-offset, f'({solution1}, {0})', ha='center', va='center')
            plt.text(solution2, 0-offset, f'({solution2}, {0})', ha='center', va='center')


        plt.title(f'A graph of {a}x² + {b}x + {c} = 0')
        plt.xlabel('x-axis')
        plt.ylabel('y-axis')
        plt.get_current_fig_manager().window.wm_geometry("+0+0")
        fig.canvas.manager.window.attributes('-topmost', 1)
        # Show plot
        plt.show()
    new_question = yes_input('New question? (y/n): ')
    if new_question == "no":
        break
2021-11-24 09:07:47

Multumesc pentru ajutor, există vreo modalitate de a obține textul de sub punctul? Am upvoted solutia ta și, dacă aveți o soluție pentru a obține textul de sub punctul de voi accepta ca cel mai bun răspuns.
Raed Ali

Pentru a face acest lucru, puteți pur și simplu substrace un offset de valoare coordonate de text. Am editat raspunsul meu să-l pună în aplicare. Dar, pentru mai complex adnotări, check-plt.adnota().
yannvm

În alte limbi

Această pagină este în alte limbi

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................