【问题标题】:Why does my graph sketching class draw sec, but not cosec or cot?为什么我的绘图课画的是秒,而不是 cosec 或 cot?
【发布时间】: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


    【解决方案1】:

    我现在已经能够解决这个问题,因为我使用子句检查输入函数的有效性:

    try:
        self.function(0)
    except (NameError, TypeError,  AttributeError, ZeroDivisionError):
        return
    

    在这里,我通过尝试计算 f(0) 来确保函数是可执行的,以便在渲染曲线时不会发生错误。但是由于 cosec(x) 和 cot(x) f(0) 是未定义的,该类没有尝试渲染曲线。这就解释了为什么在 x 上加一些量就可以绘制出来。

    为了解决这个问题,我将代码更改为这个,它分别处理零除错误。

    try:
        self.function(0)
    except (NameError, TypeError,  AttributeError):
        return
    except ZeroDivisionError:
        pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-01
      • 2012-04-21
      • 1970-01-01
      • 2021-12-19
      • 2016-10-17
      • 1970-01-01
      • 2010-12-31
      • 2013-01-03
      相关资源
      最近更新 更多