Home > Blockchain >  How can I plot a discontinuous function without a connecting line?
How can I plot a discontinuous function without a connecting line?

Time:08-12

I am using Tkinter in Python to develop a graphing calculator and I'm having some trouble with discontinuous functions. Here is my code for drawing a line from the equation tan(x) on a graph of dimensions 640x640:

for i in range(0, 640):
    x = (i - 320)/32
    try:
        y = math.tan(x)
        y = 320 - (32 * y)
        if i == 0:
            prevx = x
            prevy = y
        graph.create_line(prevx, prevy, i, y, fill='#ff0000', width=3)
        prevx = i
        prevy = y
    except ZeroDivisionError:
        pass
    except ValueError:
        pass

When I run this code Tangent Graph

Test this out and see if it meets the spirit of your project.

CodePudding user response:

Upon further investigation I have devised a solution. Here is the new code:

prevx = 0
prevy = 0
error = False
for i in range(0, 640):
    x = (i - 320)/32
    try:
        y = math.tan(x)
    except ZeroDivisionError:
        error = True
    except ValueError:
        error = True
    else:
        y = 320 - (32 * y)
        if i == 0:
            prevx = x
            prevy = y
        if error == False:
            graph.create_line(prevx, prevy, i, y, fill='#ff0000', width=3)
        else:
            graph.create_line(prevx, prevy, i, y, fill='#ff0000', width=3, state='hidden')
            error = False
        prevx = i
        prevy = y

I created a new boolean variable error to hide the line being drawn when a math error is returned. Note that this solution works for pretty much every discontinuous function including: y=1/x, y=sqrt(x) and y=log(x). However, it doesn't work for y=tan(x) as for some reason in the Python math library tan(90) doesn't produce an error (same goes for sec and cosec). I'd appreciate if anyone could figure out a way around this.

  • Related