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
JavaScript
x
43
43
1
width = 80
2
height = 30
3
canvas = [[' '] * width for i in range(height)]
4
5
def PrintCanvas():
6
for i in range(len(canvas)):
7
for j in range(len(canvas[0])):
8
print(canvas[i][j], end='')
9
print()
10
11
def execute(callback):
12
for i in range(len(canvas)):
13
for j in range(len(canvas[0])):
14
if callback(i, j):
15
canvas[i][j] = '*'
16
17
# The ratio of the height and width of the grid in the console
18
# If you don't set x=x*rate, the resulting graph will be flat
19
zoom = 819/386
20
# Since x and y are both integers, when x is multiplied by a floating-point number, y!=f(x)
21
# So we use y-f(x)<=deviation here
22
deviation = 0.5
23
24
# print x size 20
25
def fun_x(x, y):
26
r = 20
27
x *= zoom
28
return x < r and abs(y-x) <= deviation or abs(y-(-x+r-1)) <= deviation
29
30
# How to print a standard circle in the console window?
31
# print circle size 13
32
def fun_circle(x, y):
33
r = 13
34
x *= zoom
35
a = (pow(x-r, 2)+pow(y-r, 2)) - r*r
36
r = r - 2
37
b = (pow(x-r, 2)+pow(y-r, 2)) - r*r
38
return a <= 0 and b >= 0
39
40
# execute(fun_x)
41
execute(fun_circle)
42
PrintCanvas()
43
The following two pictures are the printed x shape and the wrong ring shape.
Advertisement
Answer
You are also shifting the center here
JavaScript
1
3
1
r = r - 2
2
b = (pow(x-r, 2)+pow(y-r, 2)) - r*r
3
Consider not changing the center as following
JavaScript
1
3
1
r2 = r - 2
2
b = (pow(x-r, 2)+pow(y-r, 2)) - r2*r2
3
On a side note, now you know how to draw a crescent too.