【发布时间】:2019-07-31 14:47:19
【问题描述】:
我在 Pygame 中为图形计算器编写了一个类,它本质上只是勾画了一个函数。我一直在为它开发 UI,但发现它不适用于倒数三角函数 cosec 或 cot(分别在 python 中为1/(math.sin(x)) 和1/(math.tan(x))),尽管它确实适用于 sec(1/(math.cos(x))) .
我一直在使用lambda 关键字将这些函数输入到类中。例如:c = Curve(lambda x: x**2, (255, 0, 0))
我仍在努力改进它,它目前还没有完成,而且它肯定还不是用户证明。但是,无论我尝试什么,我都无法弄清楚为什么我无法让 cosec 或 cot 使用它。
任何帮助将不胜感激,谢谢。
class Curve(object):
def __init__(self, func, colour, width=1):
self.function = func
self.colour = colour
self.width = width
def render(self, colour=None, width=None):
if self.function is None:
return
if colour is not None:
self.colour = colour
if width is not None:
self.width = width
try:
self.function(0)
except (NameError, TypeError, AttributeError, ZeroDivisionError):
return
for x in range(0, WIDTH):
try:
fx = self.function((x / camera_pos[2]) + camera_pos[0])
fx1 = self.function(((x + 1) / camera_pos[2]) + camera_pos[0])
except (OverflowError, ValueError, ZeroDivisionError):
continue
if type(fx) == complex or type(fx1) == complex:
continue
if 0 < transform_point(-fx, "y") < HEIGHT or 0 < transform_point(-fx1, "y") < HEIGHT:
pygame.draw.line(SCREEN, self.colour, (x, transform_point(-fx, "y")),
(x + 1, transform_point(-fx1, "y")), self.width)
transform_point() 函数将笛卡尔坐标映射到屏幕上的位置。
camera_pos = [-400, -300, 1] # [x, y, zoom]
def transform_point(value, axis):
if str(axis).lower() == "x":
return (value - camera_pos[0]) * camera_pos[2]
elif str(axis).lower() == "y":
return (value - camera_pos[1]) * camera_pos[2]
编辑:
我现在发现,如果你在函数中为 x 添加任何值,即使该值非常小,该类也可以工作,例如:cosec(x+0.0000000000001)
我很抱歉图像质量。
【问题讨论】:
标签: python python-3.x function class pygame