"math.floor(x)"和"int(x)"在Python中为正实数产生不同的结果吗?

Omi*_*mid 1 python random int floor

我已经检查了Python shell上的一些例子,他们似乎吐了相同的数字.但是在一个应该近似大量数字的程序中,它们显然会产生不同的结果.

我正在尝试编写一个模拟矩形平面上物体运动的小程序.为此,我必须编写一个名为"RectangularRoom"的类,它接收宽度和高度并创建一个网格:

class RectangularRoom(object):
"""
A RectangularRoom represents a rectangular region containing clean or dirty
tiles.

A room has a width and a height and contains (width * height) tiles. At any
particular time, each of these tiles is either clean or dirty.
"""
def __init__(self, width, height):
    """
    Initializes a rectangular room with the specified width and height.

    Initially, no tiles in the room have been cleaned.

    width: an integer > 0
    height: an integer > 0
    """
    self.width = width
    self.height = height
    self.room_coordinates = []
    for m in range(self.width):
        for n in range(self.height):
            self.room_coordinates.append((m,n))
    self.cleaned = []
def cleanTileAtPosition(self, pos):
    """
    Mark the tile under the position POS as cleaned.

    Assumes that POS represents a valid position inside this room.

    pos: a Position
    """
    self.cleaned.append((int(pos.getX()), int(pos.getY())))

def isTileCleaned(self, m, n):
    """
    Return True if the tile (m, n) has been cleaned.

    Assumes that (m, n) represents a valid tile inside the room.

    m: an integer
    n: an integer
    returns: True if (m, n) is cleaned, False otherwise
    """
    assert type (m)== int and type (n) == int
    return (m,n) in self.cleaned

def getNumTiles(self):
    """
    Return the total number of tiles in the room.

    returns: an integer
    """
    return self.width*self.height

def getNumCleanedTiles(self):
    """
    Return the total number of clean tiles in the room.

    returns: an integer
    """
    return len(self.cleaned)

def getRandomPosition(self):
    """ 
    Return a random position inside the room.

    returns: a Position object.
    """
    return Position (random.randrange(0 , self.width), random.randrange(0 , self.height))

def isPositionInRoom(self, pos):
    """
    Return True if pos is inside the room.

    pos: a Position object.
    returns: True if pos is in the room, False otherwise.
    """
    return (int(pos.getX()), int(pos.getY())) in self.room_coordinates
Run Code Online (Sandbox Code Playgroud)

如您所见,我使用int()方法和随机生成器"random.randrange"实现了它.

在解决方案中,教师使用math.floor()函数和随机生成器random.random()实现了这个类:

class RectangularRoom(object):
"""
A RectangularRoom represents a rectangular region containing clean or dirty
tiles.

A room has a width and a height and contains (width * height) tiles. At any
particular time, each of these tiles is either clean or dirty.
"""
def __init__(self, width, height):
    """
    Initializes a rectangular room with the specified width and height.

    Initially, no tiles in the room have been cleaned.

    width: an integer > 0
    height: an integer > 0
    """
    self.width = width
    self.height = height
    self.tiles = {}
    for x in range(self.width):
        for y in range(self.height):
            self.tiles[(x, y)] = False

def cleanTileAtPosition(self, pos):
    """
    Mark the tile under the position POS as cleaned.

    Assumes that POS represents a valid position inside this room.

    pos: a Position
    """
    x = math.floor(pos.getX())
    y = math.floor(pos.getY())
    self.tiles[(x, y)] = True

def isTileCleaned(self, m, n):
    """
    Return True if the tile (m, n) has been cleaned.

    Assumes that (m, n) represents a valid tile inside the room.

    m: an integer
    n: an integer
    returns: True if (m, n) is cleaned, False otherwise
    """
    return self.tiles[(m, n)]

def getNumTiles(self):
    """
    Return the total number of tiles in the room.

    returns: an integer
    """
    return self.width * self.height

def getNumCleanedTiles(self):
    """
    Return the total number of clean tiles in the room.

    returns: an integer
    """
    return sum(self.tiles.values())

def getRandomPosition(self):
    """
    Return a random position inside the room.

    returns: a Position object.
    """
    return Position(random.random() * self.width,
                    random.random() * self.height)

def isPositionInRoom(self, pos):
    """
    Return True if pos is inside the room.

    pos: a Position object.
    returns: True if pos is in the room, False otherwise.
    """
    return ((0 <= pos.getX() < self.width)
            and (0 <= pos.getY() < self.height))
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,这两个代码块产生了完全不同的结果.我想知道为什么会这样.int()和floor()应该对正数具有相同的效果,并且两个随机函数似乎产生类似的数字.

the*_*dog 5

好吧,我不知道你问题的答案 - 我怀疑他们的回答完全相同.但是,我认为您的解决方案存在问题,可能会解释输出:

在'cleanTileAtPosition'中

self.cleaned.append((int(pos.getX()), int(pos.getY())))
Run Code Online (Sandbox Code Playgroud)

在'getNumCleanedTiles'中

return len(self.cleaned)
Run Code Online (Sandbox Code Playgroud)

此代码似乎允许多次清理磁贴.这不是您的教师代码所做的,因为磁贴只能设置为"True"一次.

(顺便说一句,因为random.randrange返回一个整数..整数转换应该什么都不做!)

编辑:另外 - 我认为类型差异值得考虑.但是你的所有类型都是'整数',所以它应该不是问题.