Skip to main content
 首页 » 编程设计

Python Turtle Graphics,如何在一个区间内绘制函数

2025年05月04日13zdz8207

我需要在指定的时间间隔内绘制一个函数。函数为f1,如下代码所示,区间为[-7,-3]; [-1, 1]; [3, 7] 步长为 0.01。当我执行程序时,没有绘制任何东西。有任何想法吗?

import turtle 
from math import sqrt 
 
wn = turtle.Screen() 
wn.bgcolor("white") 
wn.title("Plotting") 
mypen = turtle.Turtle() 
mypen.shape("classic") 
mypen.color("black") 
mypen.speed(10) 
 
while True: 
try: 
    def f1(x): 
        return 2 * sqrt((-abs(abs(x)-1)) * abs(3 - abs(x))/((abs(x)-1)*(3-abs(x)))) * \ 
(1 + abs(abs(x)-3)/(abs(x)-3))*sqrt(1-(x/7)**2)+(5+0.97*(abs(x-0.5)+abs(x+0.5))-\ 
3*(abs(x-0.75)+abs(x+0.75)))*(1+abs(1-abs(x))/(1-abs(x))) 
 
    mypen.penup() 
 
    step=.01 
    startf11=-7 
    stopf11=-3 
    startf12=-1 
    stopf12=1 
    startf13=3 
    stopf13=7 
    def f11 (startf11,stopf11,step): 
        rc=[] 
        y = f1(startf11) 
        while y<=stopf11: 
            rc.append(startf11) 
            #y+=step 
            mypen.setpos(f1(startf11)*25,y*25) 
            mypen.dot() 
    def f12 (startf12,stopf12,step): 
        rc=[] 
        y = f1(startf12) 
        while y<=stopf12: 
            rc.append(startf12) 
            #y+=step 
            mypen.setpos(f1(startf12)*25, y*25) 
            mypen.dot() 
    def f13 (startf13,stopf13,step): 
        rc=[] 
        y = f1(startf13) 
        while y<=stopf13: 
            rc.append(startf13) 
            #y+=step 
            mypen.setpos(f1(startf13)*25, y*25) 
            mypen.dot() 
 
    f11(startf11,stopf11,step) 
    f12(startf12,stopf12,step) 
    f13(startf13,stopf13,step) 
 
except ZeroDivisionError: 
    continue 

请您参考如下方法:

我想是因为 f1 返回了一个虚数。 我实际上是在 15 分钟前才开始学习 python,我是从 turtle 开始的。所以我可能不完全理解并离开......但总的来说我理解代码......

但是是的,当您定义它时;这一点;你的第二个任期。

平方((-绝对值(绝对值(x)-1))

您正在尝试计算负数的平方根。那不在笛卡尔平面上。不知道数学如何解释它,也不知道 turtle 如何解释它,但这是我的第一个猜测......