简体   繁体   中英

Draw log base 2 graph using Python turtle graphics

I tried this:

if wave_type == "log":
  emily.up ()
  emily.goto(0,1)
  emily.down ()
  for x in range(100):
    y = math.log( x ) / math.log( 2 )
    elaine.goto(x, y)

but it didn't work. Please help

Here's a rough start -- since range() can't handle float, we use 10x the range and then divide by 10 when we use the value. (Look into arange() in numpy as a way around this.) I'm also graphing a smaller area, and using setworldcoordinates() to enforce that, so we can see the interesting part of the graph where it crosses the X-axis:

import math
from turtle import Turtle, Screen

screen = Screen()
screen.setworldcoordinates(0, -5, 10, 5)

emily = Turtle(visible=False)
emily.forward(10)
emily.penup()

for x in range(1, 100):
    y = math.log(x / 10) / math.log(2)
    emily.goto(x / 10, y)
    emily.pendown()

screen.exitonclick()

You can fill in the Y-axis, add tick marks, label axes, increase resolution, etc. as you see fit:

在此处输入图片说明

Log(0) is undefined. Hence your code will error on the first iteration of the for loop (x will be 0).

Perhaps you want range(1, 100)? Or even better have more x values around 1 as this is where the graph is changing the most for a smoother plot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM