def generate_random_points(ref_radius, total_points):
"""Return x, y coordinate lists representing random points inside a circle.
This function illustrates NumPy capabilities. It is used in the
optimization pass 4, 5, 6 in the chapter on performance of the book
Learning Python Application Development (Packt Publishing).
The run time performance of this function will be
significantly faster compared to the previous optimization pass.
Generates random points inside a circle with center at (0,0). For any
point, it randomly picks a radius between 0 and ref_radius.
:param ref_radius: The random point lies between 0 and this radius.
:param total_points: total number of random points to be created
:return: x and y coordinates as lists
.. todo:: Refactor! Move the function to a module like gameutilities.py
"""
# Combination of avoiding the dots (function reevaluations)
# and using local variable. This is similar to the
# optimization pass-3 but here we use equivalent NumPy functions.
l_uniform = np.random.uniform
l_sqrt = np.sqrt
l_pi = np.pi
l_cos = np.cos
l_sin = np.sin
# Note that the variables theta and radius are now NumPy arrays.
theta = l_uniform(0.0, 2.0*l_pi, total_points)
radius = ref_radius*l_sqrt(l_uniform(0.0, 1.0, total_points))
x = radius*l_cos(theta)
y = radius*l_sin(theta)
# Unlike optimization pass-4 (which returns x and y as Python lists,
# here it returns the NumPy arrays directly to be consumed by
# the GoldHunt.find_coins method
return x, y
goldhunt_pass5.py 文件源码
python
阅读 20
收藏 0
点赞 0
评论 0
评论列表
文章目录