📌  相关文章
📜  Sin , Cos Graph 使用 python turtle. - Python (1)

📅  最后修改于: 2023-12-03 14:47:27.711000             🧑  作者: Mango

Sin and Cos Graph using Python Turtle

Python Turtle is a module in Python that allows us to create graphics and shapes on the screen using turtle graphics. In this tutorial, we will learn how to use Python Turtle to create a sin and cos graph.

Introduction

Before we dive into the code, let's go over what a sin and cos graph is. A sin graph is a graph of the sine function, which is a periodic function that oscillates between 1 and -1. A cos graph is a graph of the cosine function, which is also a periodic function that oscillates between 1 and -1 but has a phase shift of pi/2.

Code

To create the sin and cos graph using Python Turtle, we will first import the turtle module and set up the window and turtle objects.

import turtle

# Set up the window
win = turtle.Screen()
win.setup(width=600, height=400)
win.title("Sin and Cos Graph using Python Turtle")

# Set up the turtle object
t = turtle.Turtle()
t.speed(0)

Next, we will define a function to create the graph. We will use a for loop to iterate through a range of x values, and for each x value, we will calculate the corresponding y values for the sin and cos functions. We will then use the turtle object to draw lines between the points.

def sin_cos_graph(amplitude, frequency, phase):
    # Set up the starting position
    x_start = -300
    y_start = amplitude * (0 - phase)

    # Move the turtle to the starting position
    t.penup()
    t.goto(x_start, y_start)
    t.pendown()

    # Draw the sin and cos graph
    for x in range(x_start, 300):
        # Calculate the y values for sin and cos
        y_sin = amplitude * math.sin(frequency * (x - x_start) * math.pi / 180.0 - phase)
        y_cos = amplitude * math.cos(frequency * (x - x_start) * math.pi / 180.0 - phase)

        # Draw the sin and cos lines
        t.goto(x, y_sin)
        t.pencolor("red")
        t.pensize(2)
        t.forward(1)

        t.goto(x, y_cos)
        t.pencolor("blue")
        t.pensize(2)
        t.forward(1)

# Call the function
sin_cos_graph(50, 2, 0)

In the function sin_cos_graph, we pass in three parameters: amplitude, frequency, and phase. These parameters determine the properties of the graph, such as the amplitude and frequency of the functions.

Conclusion

That's it! You now know how to create a sin and cos graph using Python Turtle. You can experiment with different values for the parameters to create different graphs. You can also add more features to the graph, such as axis labels and a legend, to make it more informative.