I am trying to print an arbitrary math function through a callback function, the execute() function will iterate over all integer coordinates (x,y), if the callback returns true then canvas[x][y] = ‘*’.
But my implementation only works when printing straight lines, always fails to print hollow circles
width = 80 height = 30 canvas = [[' '] * width for i in range(height)] def PrintCanvas(): for i in range(len(canvas)): for j in range(len(canvas[0])): print(canvas[i][j], end='') print() def execute(callback): for i in range(len(canvas)): for j in range(len(canvas[0])): if callback(i, j): canvas[i][j] = '*' # The ratio of the height and width of the grid in the console # If you don't set x=x*rate, the resulting graph will be flat zoom = 819/386 # Since x and y are both integers, when x is multiplied by a floating-point number, y!=f(x) # So we use y-f(x)<=deviation here deviation = 0.5 # print x size 20 def fun_x(x, y): r = 20 x *= zoom return x < r and abs(y-x) <= deviation or abs(y-(-x+r-1)) <= deviation # How to print a standard circle in the console window? # print circle size 13 def fun_circle(x, y): r = 13 x *= zoom a = (pow(x-r, 2)+pow(y-r, 2)) - r*r r = r - 2 b = (pow(x-r, 2)+pow(y-r, 2)) - r*r return a <= 0 and b >= 0 # execute(fun_x) execute(fun_circle) PrintCanvas()
The following two pictures are the printed x shape and the wrong ring shape.
Advertisement
Answer
You are also shifting the center here
r = r - 2 b = (pow(x-r, 2)+pow(y-r, 2)) - r*r
Consider not changing the center as following
r2 = r - 2 b = (pow(x-r, 2)+pow(y-r, 2)) - r2*r2
On a side note, now you know how to draw a crescent too.