S
S
Sergey Pavlov2014-01-20 22:27:08
Python
Sergey Pavlov, 2014-01-20 22:27:08

Why doesn't the chart drawing code work?

The code is taken from Habr ( habrahabr.ru/post/163395 ), the program is a primitive graph drawer written in Python 2.7.4 using the Tkinter library to create a GUI. The value of the function should be calculated at each of 16,000 points, with subsequent transfer to the graph.
But it doesn't happen. Where is the mistake?

from math import *
from Tkinter import *


f = raw_input('f(x):')

root = Tk()

canv = Canvas(root, width = 1000, height = 1000, bg = "white")
canv.create_line(500,1000,500,0,width=2,arrow=LAST) 
canv.create_line(0,500,1000,500,width=2,arrow=LAST)

First_x = -500;

for i in range(16000):
    if (i % 800 == 0):
        k = First_x + (1 / 16) * i
        canv.create_line(k + 500, -3 + 500, k + 500, 3 + 500, width = 0.5, fill = 'black')
        canv.create_text(k + 515, -10 + 500, text = str(k), fill="purple", font=("Helvectica", "10"))
        if (k != 0):
            canv.create_line(-3 + 500, k + 500, 3 + 500, k + 500, width = 0.5, fill = 'black')
            canv.create_text(20 + 500, k + 500, text = str(k), fill="purple", font=("Helvectica", "10"))
    try:
        x = First_x + (1 / 16) * i
        new_f = f.replace('x', str(x))
        y = -eval(new_f) + 500
        x += 500
        canv.create_oval(x, y, x + 1, y + 1, fill = 'black')
    except:
        pass
canv.pack()
root.mainloop()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
throughtheether, 2014-01-21
@Pavlov_dog

>k = First_x + (1 / 16) * i
This is always equal to First_x because 1/16 always (python 2.7) results in 0. Correct to k = First_x + i/16
> x = First_x + (1 / 16) * i
Similarly. Correct to x = First_x + i/16.
In answer to your question, the code doesn't work because in python3.x (example in the link) and python 2.x (your version), the / operator works differently. Another solution to the problem is to leave the code untouched, add only the line
from __future__ import division to the beginning

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question