填充ci所需的完整和部分sqare磁贴的数量

2024-06-11 22:54:12 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python3,我想知道在给定半径r的圆形区域中,需要多少个完整的和多少个偏方形的瓷砖(边长为1个单位)。多个部分分块不能相加形成一个完整的分片,部分分片的其余部分也不能在其他地方重用。在

圆的中心总是在四个平铺之间的边界上,所以我们可以计算出圆的1/4的需要量,然后乘以4。在

因此,如果r=1,则有0个完整的分片和4个部分的分片。
对于r=2,结果将是4个完整的分片和12个部分的分片,依此类推。。。在

我可以使用什么方法?代码应该尽可能短。在


Tags: 区域地方半径单位圆形中心分块python3
1条回答
网友
1楼 · 发布于 2024-06-11 22:54:12

我认为下面的方法可以解决这个问题。很抱歉print语句是python2,但我认为它应该很容易转换。在

import math

# Input argument is the radius
circle_radius = 2.

# This is specified as 1, but doesn't have to be
tile_size = 1.

# Make a square box covering a quarter of the circle
tile_length_1d = int(math.ceil(circle_radius / tile_size ))

# How many tiles do you need?
num_complete_tiles = 0
num_partial_tiles = 0

# Now loop over all tile_length_1d x tile_length_1d tiles and check if they
# are needed
for i in range(tile_length_1d):
    for j in range(tile_length_1d):
        # Does corner of tile intersect circle?
        intersect_len = ((i * tile_size)**2 + (j * tile_size)**2)**0.5
        # Does *far* corner intersect (ie. is the whole tile in the circle)
        far_intersect_len = (((i+1) * tile_size)**2 + ((j+1) * tile_size)**2)**0.5
        if intersect_len > circle_radius:
            # Don't need tile, continue
            continue
        elif far_intersect_len > circle_radius:
            # Partial tile
            num_partial_tiles += 1
        else:
            # Keep tile. Maybe you want to store this or something
            # instead of just adding 1 to count?
            num_complete_tiles += 1

# Multiple by 4 for symmetry
num_complete_tiles = num_complete_tiles * 4
num_partial_tiles = num_partial_tiles * 4

print "You need %d complete tiles" %(num_complete_tiles)
print "You need %d partial tiles" %(num_partial_tiles)

相关问题 更多 >