text
stringlengths
1
7.76k
source
stringlengths
17
81
23. Metric data structures Exhibit 23.4: The search for a record with key values (1903, v) starts with the scales and proceeds via the directory to the correct data bucket on disk. The dynamics of splitting and merging The dynamic behavior of the grid file is best explained by tracing an example: we show the effect of repeated insertions in a two-dimensional file. Instead of showing the grid directory, whose elements are in one-to-one correspondence with the grid blocks, we draw the bucket pointers as originating directly from the grid blocks. Initially, a single bucket A, of capacity c = 3 in our example, is assigned to the entire domain (Exhibit 23.5). When bucket A overflows, the domain is split, a new bucket B is made available, and those records that lie in one half of the space are moved from the old bucket to the new one (Exhibit 23.6). If bucket A overflows again, its grid block (i.e. the left half of the space) is split according to some splitting policy: We assume the simplest splitting policy of alternating directions. Those records of A that lie in the lower-left grid block of Exhibit 23.7 are moved to a new bucket C. Notice that as bucket B did not overflow, it is left alone: Its region now consists of two grid blocks. For effective memory utilization it is essential that in the process of refining the grid partition we need not necessarily split a bucket when its region is split. Exhibit 23.5: A growing grid file starts with a single bucket allocated to the entire key space. 261
algorithms and data structures_Page_261_Chunk4801
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 23.6: An overflowing bucket triggers a refinement of the space partition. Exhibit 23.7: Bucket A has been split into A and C, but the contents of B remain unchanged. Assuming that records keep arriving in the lower-left corner of the space, bucket C will overflow. This will trigger a further refinement of the grid partition as shown in Exhibit 23.8, and a splitting of bucket C into C and D. The history of repeated splitting can be represented in the form of a binary tree, which imposes on the set of buckets currently in use (and hence on the set of regions of these buckets) a twin system (also called a buddy system): Each bucket and its region have a unique twin from which it split off. In Exhibit 23.8, C and D are twins, the pair (C, D) is A's twin, and the pair (A, (C, D)) is B's twin. Exhibit 23.8: Bucket regions that span several cells ensure high disk utilization. Deletions trigger merging operations. In contrast to one-dimensional storage, where it is sufficient to merge buckets that split earlier, merging policies for multidimensional grid files need to be more general in order to maintain a high occupancy. Algorithms and Data Structures 262 A Global Text
algorithms and data structures_Page_262_Chunk4802
23. Metric data structures Simple geometric objects and their parameter spaces Consider a class of simple spatial objects, such as aligned rectangles in the plane (i.e. with sides parallel to the axes). Within its class, each object is defined by a small number of parameters. For example, an aligned rectangle is determined by its center (cx, cy) and the half-length of each side, dx and dy. An object defined within its class by k parameters can be considered to be a point in a k-dimensional parameter space. For example, an aligned rectangle becomes a point in four-dimensional space. All of the geometric and topological properties of an object can be deduced from the class it belongs to and from the coordinates of its corresponding point in parameter space. Different choices of the parameter space for the same class of objects are appropriate, depending on characteristics of the data to be processed. Some considerations that may determine the choice of parameters are: 1. Distinction between location parameters and extension parameters. For some classes of simple objects it is reasonable to distinguish location parameters, such as the center (cx, cy) of an aligned rectangle, from extension parameters, such as the half-sides dx and dy. This distinction is always possible for objects that can be described as Cartesian products of spheres of various dimensions. For example, a rectangle is the product of two one-dimensional spheres, a cylinder the product of a one-dimensional and a two- dimensional sphere. Whenever this distinction can be made, cone-shaped search regions generated by proximity queries as described in the next section have a simple intuitive interpretation: The subspace of the location parameters acts as a "mirror" that reflects a query. 2. Independence of parameters, uniform distribution. As an example, consider the class of all intervals on a straight line. If intervals are represented by their left and right endpoints, lx and rx, the constraint lx ≤ rx restricts all representations of these intervals by points (lx, rx) to the triangle above the diagonal. Any data structure that organizes the embedding space of the data points, as opposed to the particular set of points that must be stored, will pay some overhead for representing the unpopulated half of the embedding space. A coordinate transformation that distributes data all over the embedding space leads to more efficient storage. The phenomenon of nonuniform data distribution can be worse than this. In most applications, the building blocks from which complex objects are built are much smaller than the space in which they are embedded, as the size of a brick is small compared to the size of a house. If so, parameters such as lx and rx that locate boundaries of an object are highly dependent on each other. Exhibit 23.9 shows short intervals on a long line clustering along the diagonal, leaving large regions of a large embedding space unpopulated; whereas the same set of intervals represented by a location parameter cx and an extension parameter dx fills a smaller embedding space in a much more uniform way. With the assumption of bounded dx, this data distribution is easier to handle. 263
algorithms and data structures_Page_263_Chunk4803
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 23.9: A set of intervals represented in two different parameter spaces. Region queries of arbitrary shape Intersection is a basic component of other proximity queries, and thus deserves special attention. CAD design rules, for example, often require different objects to be separated by some minimal distance. This is equivalent to requiring that objects surrounded by a rim do not intersect. Given a subset Γ of a class of simple spatial objects with parameter space H, we consider two types of queries: • point query Given a query point q, find all objects A ∈ Γ for which q ∈ A. • point set query Given a query set Q of points, find all objects A ∈ Γ that intersect Q. Point query. For a query point q compute the region in H that contains all points representing objects in Γ that overlap q. 1. Consider the class of intervals on a straight line. An interval given by its center cx and its half length dx overlaps a point q with coordinate qx if and only if cx – dx ≤ qx ≤ cx + dx. 2. The class of aligned rectangles in the plane (with parameters cx, cy, dx, dy) can be treated as the Cartesian product of two classes of intervals, one along the x-axis, the other along the y-axis (Exhibit 23.10). All rectangles that contain a given point q are represented by points in four-dimensional space that lie in the Cartesian product of two point-in-interval query regions. The region is shown by its projections onto the cx- dx plane and the cy-dy plane. Algorithms and Data Structures 264 A Global Text
algorithms and data structures_Page_264_Chunk4804
23. Metric data structures Exhibit 23.10: A set of aligned rectangles represented as a set of points in a four-dimensional parameter space. A point query is transformed into a cone-shaped region query. 3. Consider the class of circles in the plane. We represent a circle as a point in three-dimensional space by the coordinates of its center (cx, cy) and its radius r as parameters. All circles that overlap a point q are represented in the corresponding three-dimensional space by points that lie in the cone with vertex q shown in Exhibit 23.11. The axis of the cone is parallel to the r-axis (the extension parameter), and its vertex q is considered a point in the cx-cy plane (the subspace of the location parameters). Exhibit 23.11: Search cone for a point query for circles in the plane. Point set query. Given a query set Q of points, the region in H that contains all points representing objects A ∈ Γ that intersect Q is the union of the regions in H that results from the point queries for each point q ∈ Q. The union of cones is a particularly simple region in H if the query set Q is a simple spatial object. 265
algorithms and data structures_Page_265_Chunk4805
This book is licensed under a Creative Commons Attribution 3.0 License 1. Consider the class of intervals on a straight line. An interval i = (cx, dx) intersects a query interval Q = (cq, dq) if and only if its representing point lies in the shaded region shown in Exhibit 23.12; this region is given by the inequalities cx – dx ≤ cq + dq and cx + dx ≥ cq – dq. Exhibit 23.12: An interval query, as a union of point queries, again gets transformed into a search cone. 2. The class of aligned rectangles in the plane is again treated as the Cartesian product of two classes of intervals, one along the x-axis, the other along the y-axis. If Q is also an aligned rectangle, all rectangles that intersect Q are represented by points in four-dimensional space lying in the Cartesian product of two interval intersection query regions. 3. Consider the class of circles in the plane. All circles that intersect a line segment L are represented by points lying in the cone-shaped solid shown in Exhibit 23.13. This solid is obtained by embedding L in the cx-cy plane, the subspace of the location parameters, and moving the cone with vertex at q along L. Algorithms and Data Structures 266 A Global Text
algorithms and data structures_Page_266_Chunk4806
23. Metric data structures Exhibit 23.13: Search region as a union of cones. Evaluating region queries with a grid file We have seen that proximity queries on spatial objects lead to search regions significantly more complex than orthogonal range queries. The grid file allows the evaluation of irregularly shaped search regions in such a way that the complexity of the region affects CPU time but not disk accesses. The latter limits the performance of a data base implementation. A query region Q is matched against the scales and converted into a set I of index tuples that refer to entries in the directory. Only after this preprocessing do we access disk to retrieve the correct pages of the directory and the correct data buckets whose regions intersect Q (Exhibit 23.14). Exhibit 23.14: The cells of a grid partition that overlap an arbitrary query region Q are determined by merely looking up the scales. Interaction between query processing and data access The point of the two preceding sections was to show that in a metric data structure, intricate computations triggered by proximity queries can be preprocessed to a remarkable extent before the objects involved are retrieved. 267
algorithms and data structures_Page_267_Chunk4807
This book is licensed under a Creative Commons Attribution 3.0 License Query preprocessing may involve a significant amount of computation based on small amounts of auxiliary data— the scales and the query—that are kept in central memory. The final access of data from disk is highly selective— data retrieved has a high chance of being part of the answer. Contrast this to an approach where an object can be accessed only by its name (e.g. the part number) because the geometric information about its location in space is only included in the record for this object but is not part of the accessing mechanism. In such a database, all objects might have to be retrieved in order to determine which ones answer the query. Given that disk access is the bottleneck in most database applications, it pays to preprocess queries as much as possible in order to save disk accesses. The integration of query processing and accessing mechanism developed in the preceding sections was made possible by the assumption of simple objects, where each instance is described by a small number of parameters. What can we do when faced with a large number of irregularly shaped objects? Complex, irregularly shaped spatial objects can be represented or approximated by simpler ones in a variety of ways, for example: decomposition, as in a quad tree tessellation of a figure into disjoint raster squares; representation as a cover of overlapping simple shapes; and enclosing each object in a container chosen from a class of simple shapes. The container technique allows efficient processing of proximity queries because it preserves the most important properties for proximity-based access to spatial objects, in particular: It does not break up the object into components that must be processed separately, and it eliminates many potential tests as unnecessary (if two containers don't intersect, the objects within won't either). As an example, consider finding all polygons that intersect a given query polygon, given that each of them is enclosed in a simple container such as a circle or an aligned rectangle. Testing two polygons for intersection is an expensive operation compared to testing their containers for intersection. The cheap container test excludes most of the polygons from an expensive, detailed intersection check. Any approximation technique limits the primitive shapes that must be stored to one or a few types: for example, aligned rectangles or boxes. An instance of such a type is determined by a few parameters, such as coordinates of its center and its extension, and can be considered to be a point in a (higher-dimensional) parameter space. This transformation reduces object storage to point storage, increasing the dimensionality of the problem without loss of information. Combined with an efficient multi-dimensional data structure for point storage it is the basis for an effective implementation of databases for spatial objects. Exercises 1. Draw three quadtrees, one for each of the 4 · 8 pixel rectangles A, B and C outlined in Exhibit 23.15. Algorithms and Data Structures 268 A Global Text
algorithms and data structures_Page_268_Chunk4808
23. Metric data structures Exhibit 23.15: The location of congruent objects greatly affects the complexity of a quadtree representation. 2. Consider a grid file that stores points lying in a two-dimensional domain: the Cartesian product X1 × X2, where X1 = 0 .. 15 and X2 = 0 .. 15 are subranges of the integers. Buckets have a capacity of two points. (a) Insert the points (2, 3), (13, 14), (3, 5), (6, 9), (10, 13), (11, 5), (14, 9), (7, 3), (15, 11), (9, 9), and (11, 10) into the initially empty grid file and show the state of the scales, the directory, and the buckets after each insert operation. Buckets are split such that their shapes remain as quadratic as possible. (b) Delete the points (10, 13), (9, 9), (11, 10), and (14, 9) from the grid file obtained in a) and show the state of the scales, the directory, and the buckets after each delete operation. Assume that after deleting a point in a bucket this bucket may be merged with a neighbor bucket if their joint occupancy does not exceed two points. Further, a boundary should be removed from its scale if there is no longer a bucket that is split with respect to this boundary. (c) Without imposing further restrictions a deadlock situation may occur after a sequence of delete operations: No bucket can merge with any of its neighbors, since the resulting bucket region would no longer be rectangular. In the example shown in Exhibit 23.16 the shaded ovals represent bucket regions. Devise a merging policy that prevents such deadlocks from occurring in a two-dimensional grid file. 269
algorithms and data structures_Page_269_Chunk4809
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 23.16: This example shows bucket regions that cannot be merged pairwise. 3. Consider the class of circles in the plane represented as points in three-dimensional parameter space as proposed in chapter 23 in the section “Region queries of arbitrary shape”. Describe the search regions in the parameter space (a) for all the circles intersecting a given circle C, (b) for all the circles contained in C, and (c) for all the circles enclosing . Algorithms and Data Structures 270 A Global Text
algorithms and data structures_Page_270_Chunk4810
This book is licensed under a Creative Commons Attribution 3.0 License Part VI: Interaction between algorithms and data structures: case studies in geometric computation Organizing and processing Euclidean space In Part III we presented a varied sample of algorithms that use simple, mostly static, data structures. Part V was dedicated to dynamic data structures, and we presented the corresponding access and update algorithms. In this final part we illustrate the use of these dynamic data structures by presenting algorithms whose efficiency depends crucially on them, in particular on priority queues and dictionaries. We choose these algorithms from computational geometry, a recently developed discipline of great practical importance with applications in computer graphics, computer-aided design, and geographic databases. If data structures are tools for organizing sets of data and their relationships, geometric data processing poses one of the most challenging tests. The ability to organize data embedded in the Euclidean space in such a way as to reflect the rich relationships due to location (e.g. touching or intersecting, contained in, distance) is of utmost importance for the efficiency of algorithms for processing spatial data. Data structures developed for traditional commercial data processing were often based on the concept of one primary key and several subordinate secondary keys. This asymmetry fails to support the equal role played by the Cartesian coordinate axes x, y, z, … of Euclidean space. If one spatial axis, say x, is identified as the primary key, there is a danger that queries involving the other axes, say y and z, become inordinately cumbersome to process, and therefore slow. For the sake of simplicity we concentrate on two-dimensional geometric problems, and in particular on the highly successful class of plane- sweep algorithms. Sweep algorithms do a remarkably good job at processing two-dimensional space efficiently using two distinct one-dimensional data structures, one for organizing the x-axis, the other for the y-axis. Algorithms and Data Structures 271 A Global Text
algorithms and data structures_Page_271_Chunk4811
This book is licensed under a Creative Commons Attribution 3.0 License 24. Sample problems and algorithms Learning objectives: • The nature of geometric computation: three problems and algorithms chosen to illustrate the variety of issues encountered: • Convex hull yields to simple and efficient algorithms, straightforward to implement and analyze. • Objects with special properties, such as convexity, are often much simpler to process than are general objects. • Visibility problems are surprisingly complex; even if this complexity does not show in the design of an algorithm, it sneaks into its analysis. Geometry and geometric computation Classical geometry, shaped by the ancient Greeks, is more axiomatic than constructive: It emphasizes axioms, theorems, and proofs, rather than algorithms. The typical statement of Euclidean geometry is an assertion about all geometric configurations with certain properties (e.g. the theorem of Pythagoras: "In a right-angled triangle, the square on the hypotenuse c is equal to the sum of the squares on the two catheti a and b: c 2 = a2 + b2") or an assertion of existence (e.g. the parallel axiom: "Given a line L and a point P ∉ L, there is exactly one line parallel to L passing through P"). Constructive solutions to problems do occur, but the theorems about the impossibility of constructive solutions steal the glory: "You cannot trisect an arbitrary angle using ruler and compass only," and the proverbial "It is impossible to square the circle." Computational geometry, on the other hand, starts out with problems of construction so simple that, until the 1970s, they were dismissed as trivial: "Given n line segments in the plane, are they free of intersections? If not, compute (construct) all intersections." This problem is only trivial with respect to the existence of a constructive solution. As we will soon see, the question is far from trivial if interpreted as: How efficiently can we obtain the answer? Computational geometry has some appealing features that make it ideal for learning about algorithms and data structures: (a) The problem statements are easily understood, intuitively meaningful, and mathematically rigorous; right away the student can try his own hand at solving them, without having to worry about hidden subtleties or a lot of required background knowledge. (b) Problem statement, solution, and every step of the construction have natural visual representations that support abstract thinking and help in detecting errors of reasoning. (c) These algorithms are practical; it is easy to come up with examples where they can be applied. Appealing as geometric computation is, writing geometric programs is a demanding task. Two traps lie hiding behind the obvious combinatorial intricacies that must be mastered, and they are particularly dangerous when they occur together: (a) degenerate configurations, and (b) the pitfalls of numerical computation due to discretization and rounding errors. Degenerate configurations, such as those we discussed in “Straight lines and circles” on Algorithms and Data Structures 272 A Global Text
algorithms and data structures_Page_272_Chunk4812
24. Sample problems and algorithms intersecting line segments, are special cases that often require special code. It is not always easy to envision all the kinds of degeneracies that may occur in a given problem. A configuration may be degenerate for a specific algorithm, whereas it may be nondegenerate for a different algorithm solving the same problem. Rounding errors tend to cause more obviously disastrous consequences in geometric computation than, say, in linear algebra or differential equations. Whereas the traditional analysis of rounding errors focuses on bounding their cumulative value, geometry is concerned primarily with a stringent all-or-nothing question: Have errors impaired the topological consistency of the data? (Remember the pathology of the braided straight lines.) In this Part VI we aim to introduce the reader to some of the central ideas and techniques of computational geometry. For simplicity's sake we limit coverage to two-dimensional Euclidean geometry - most problems become a lot more complicated when we go from two- to three-dimensional configurations. We focus on a type of algorithm that is remarkably well suited for solving two-dimensional problems efficiently: sweep algorithms. To illustrate their generality and effectiveness, we use plane-sweep to solve several rather distinct problems. We will see that sweep algorithms for different problems can be assembled from the same building blocks: a skeleton sweep program that sweeps a line across the plane based on a queue of events to be processed, and transition procedures that update the data structures (a dictionary or table, and perhaps other structures) at each event and maintain a geometric invariant. Sweeps show convincingly how the dynamic data structures of Part V are essential for the efficiency. The problems and algorithms we discuss deal with very simple objects: points and line segments. Applications of geometric computation such as CAD, on the other hand, typically deal with very complex objects made up of thousands of polygons. The simplicity of these algorithms does not deter from their utility. Complex objects get processed by being broken into their primitive parts, such as points, line segments, and triangles. The algorithms we present are some of the most basic subroutines of geometric computation, which play a role analogous to that of a square root routine for numerical computation: As they are called untold times, they must be correct and efficient. Convex hull: a multitude of algorithms The problem of computing the convex hull H(S) of a set S consisting of n points in the plane serves as an example to demonstrate how the techniques of computational geometry yield the concise and elegant solution that we presented in “Algorithm animation”. The convex hull of a set S of points in the plane is the smallest convex polygon that contains the points of S in its interior or on its boundary. Imagine a nail sticking out above each point and a tight rubber band surrounding the set of nails. Many different algorithms solve this simple problem. Before we present in detail the algorithm that forms the basis of the program 'ConvexHull' of chapter 3, we briefly illustrate the main ideas behind three others. Most convex hull algorithms have an initialization step that uses the fact that we can easily identify two points of S that lie on the convex hull H(S): for example, two points Pmin and Pmax with minimal and maximal x-coordinate, respectively. Algorithms that grow convex hulls over increasing subsets can use the segment as a (degenerate) convex hull to start with. Other algorithms use the segment to partition S into an upper and a lower subset, and compute the upper and the lower part of the hull H(S) separately. 1. Jarvis's march [Jar 73] starts at a point on H(S), say Pmin, and 'walks around' by computing, at each point P, the next tangent to S, characterized by the property that all points of S lie on the same side of PQ 273
algorithms and data structures_Page_273_Chunk4813
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 24.1: The "gift-wrapping" approach to building the convex hull. 2. Divide-and-conquer comes to mind: Sort the points of S according to their x-coordinate, use the median x- coordinate to partition S into a left half SL and a right half SR, apply this convex hull algorithm recursively to each half, and merge the two solutions H(SL) and H(SR) by computing the two common exterior tangents to H(SL) and H(SR) (Exhibit 24.2). Terminate the recursion when a set has at most three points. Exhibit 24.2: Divide-and-conquer applies to many problems on spatial data. 3. Quickhull [Byk 78], [Edd 77], [GS 79] uses divide-and-conquer in a different way. We start with two points on the convex hull H(S), say Pmin and Pmax. In general, if we know ≥ 2 points on H(S), say P, Q, R in Exhibit 24.3, these define a convex polygon contained in H(S). (Draw the appropriate picture for just two points Pmin and Pmax on the convex hull.) There can be no points of S in the shaded sectors that extend outward from the vertices of the current polygon, PQR in the example. Any other points of S must lie either in the polygon PQR or in the regions extending outward from the sides. Exhibit 24.3: Three points known to lie on the convex hull identify regions devoid of points. For each side, such as PQ in Exhibit 24.4, let T be a point farthest from PQ among all those in the region extending outward from PQ, if there are any. T must lie on the convex hull, as is easily seen by considering Algorithms and Data Structures 274 A Global Text
algorithms and data structures_Page_274_Chunk4814
24. Sample problems and algorithms the parallel to PQ that passes through T. Having processed the side PQ, we extend the convex polygon to include T, and we now must process 2 additional sides,PT and TQ. The reader will observe a formal analogy between quicksort (“Sorting and its complexity”) and quickhull, which has given the latter its name. Exhibit 24.4: The point T farthest from identifies a new region of exclusion (shaded). 4. In an incremental scan or sweep we sort the points of S according to their x-coordinates, and use the segment PminPmax to partition S into an upper subset and a lower subset, as shown in Exhibit 24.5. For simplicity of presentation, we reduce the problem of computing H(S) to the two separate problems of computing the upper hull U(S) [i.e. the upper part of H(S)], shown in bold, and the lower hull L(S), drawn as a thin line. Our notation and pictures are chosen to describe U(S). Exhibit 24.5: Separate computations for the upper hull and the lower hull. Let P1, … , Pn be the points of S sorted by x-coordinate, and let Ui = U(P1, … , Pi) be the upper hull of the first i points. U1 = P1 may serve as an initialization. For i = 2 to n we compute Ui from Ui–1, as Exhibit 24.6 shows. Starting with the tentative tangent PiPi–1 shown as a thin dashed line, we retrace the upper hull U i–1 until we reach the actual tangent: in our example, the bold dashed line PiP2. The tangent is characterized by the fact that for j = 1, … , i–1, it minimizes the angle Ai,j between PiPj and the vertical. 275
algorithms and data structures_Page_275_Chunk4815
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 24.6: Extending the partial upper hull U(P1, … , Pi–1) to the next point Pi The program 'ConvexHull' presented in “Algorithm animation” as an example for algorithm animation is written as an on-line algorithm: Rather than reading all the data before starting the computation, it accepts one point at a time, which must lie to the right of all previous ones, and immediately extends the hull U i–1 to obtain Ui. Thanks to the input restriction that the points are entered in sorted order, 'ConvexHull' becomes simpler and runs in linear time. This explains the two-line main body: PointZero; { sets first point and initializes all necessary variables } while NextRight do ComputeTangent; There remain a few programming details that are best explained by relating Fig. 24.6 to the declarations: var x, y, dx, dy: array[0 .. nmax] of integer; b: array[0 .. nmax] of integer; { backpointer } n: integer; { number of points entered so far } px, py: integer; { new point } The coordinates of the points Pi are stored in the arrays x and y. Rather than storing angles such as Ai,j, we store quantities proportional to cos(Ai,j) and sin(Ai,j) in the arrays dx and dy. The array b holds back pointers for retracing the upper hull back toward the left: b[i] = j implies that Pj is the predecessor of Pi in Ui. This explains the key procedure of the program: procedure ComputeTangent; { from Pn = (px, py) to Un–1 } var i: integer; begin i := b[n]; while dy[n] · dx[i] > dy[i] · dx[n] do begin { dy[n]/dx[n] > dy[i]/dx[i] } i := b[i]; Algorithms and Data Structures 276 A Global Text
algorithms and data structures_Page_276_Chunk4816
24. Sample problems and algorithms dx[n] := x[n] – x[i]; dy[n] := y[n] – y[i]; MoveTo(px, py); Line(–dx[n], –dy[n]); b[n] := i end; MoveTo(px, py); PenSize(2, 2); Line(–dx[n], –dy[n]); PenNormal end; { ComputeTangent } The algorithm implemented by 'ConvexHull' is based on Graham's scan [Gra 72], where the points are ordered according to the angle as seen from a fixed internal point, and on [And 79]. The uses of convexity: basic operations on polygons The convex hull of a set of points or objects (i.e. the smallest convex set that contains all objects) is a model problem in geometric computation, with many algorithms and applications. Why? As we stated in the introductory section, applications of geometric computation tend to deal with complex objects that often consist of thousands of primitive parts, such as points, line segments, and triangles. It is often effective to approximate a complex configuration by a simpler one, in particular, to package it in a container of simple shape. Many proximity queries can be answered by processing the container only. One of the most frequent queries in computer graphics, for example, asks what object, if any, is first struck by a given ray. If we find that the ray misses a container, we infer that it misses all objects in it without looking at them; only if the ray hits the container do we start the costly analysis of all the objects in it. The convex hull is often a very effective container. Although not as simple as a rectangular box, say, convexity is such a strong geometric property that many algorithms that take time O(n) on an arbitrary polygon of n vertices require only time O(log n) on convex polygons. Let us list several such examples. We assume that a polygon G is given as a (cyclic) sequence of n vertices and/or n edges that trace a closed path in the plane. Polygons may be self- intersecting, whereas simple polygons may not. A simple polygon partitions the plane into two regions: the interior, which is simply connected, and the exterior, which has a hole. Point-in-polygon test Given a simple polygon G and a query point P (not on G), determine whether P lies inside or outside the polygon. Two closely related algorithms that walk around the polygon solve this problem in time O(n). The first one computes the winding number of G around P. Imagine an observer at P looking at a vertex, say V, where the walk starts, and turning on her heels to keep watching the walker (Exhibit 24.7). The observer will make a first (positive) turn α, followed by a (negative) turn β, followed by … , until the walker returns to the starting vertex V. The sum α + β + … of all turning angles during one complete tour of G is: 2·π if P is inside G, and 0 if P is outside G. 277
algorithms and data structures_Page_277_Chunk4817
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 24.7: Point-in polygon test by adding up all turning angles. The second algorithm computes the crossing number of G with respect to P. Draw a semi-infinite ray R from P in any direction (Exhibit 24.8). During the walk around the polygon G from an arbitrary starting vertex V back to V, keep track of whether the current oriented edge intersects R, and if so, whether the edge crosses R from below (+1) or from above (–1). The sum of all these numbers is +1 if P is inside G, and 0 if P is outside G. Exhibit 24.8: Point-in polygon test by adding up crossing numbers. Point-in-convex-polygon test For a convex polygon Q we use binary search to perform a point-in-polygon test in time O(log n). Consider the hierarchical decomposition of Q illustrated by the convex 12-gon shown in Exhibit 24.9. We choose three (approximately) equidistant vertices as the vertices of an innermost core triangle, painted black. "Equidistant" here refers not to any Euclidean distance, but rather to the number of vertices to be traversed by traveling along the perimeter of Q. For a query point P we first ask, in time O(1), which of the seven regions defined by the extended edges of this triangular core contains P. These seven regions shown in Exhibit 24.10 are all "triangles" (albeit six of them extend to infinity), in the sense that each one is defined as the intersection of three half-spaces. Four of these regions provide a definite answer to the query "Is P inside Q, or outside Q?" One region (shown hatched in Exhibit 24.10) provides the answer 'In', three the answer 'Out'. The remaining three regions, labeled 'Uncertain', lead recursively to a new point-in-convex-polygon test, for the same query point P, but a new convex polygon Q' which is Algorithms and Data Structures 278 A Global Text
algorithms and data structures_Page_278_Chunk4818
24. Sample problems and algorithms the intersection of Q with one of the uncertain regions. As Q' has only about n / 3 vertices, the depth of recursion is O(log n). Actually, after the first comparison against the innermost triangular core of Q, we have no longer a general point-in-convex-polygon problem, but one with additional information that makes all but the first test steps of a binary search. Exhibit 24.9: Hierarchical approximation of a convex 12-gon as a 3-level tree of triangles. The root is in black, its children are in dark grey, grandchildren in light grey. Exhibit 24.10: The plane partitioned into four regions of certainty and three of uncertainty. The latter are processed recursively. Visibility in the plane: a simple algorithm whose analysis is not Many computer graphics programs are dominated by visibility problems: Given a configuration of objects in three-dimensional space, and given a point of view, what is visible? Dozens of algorithms for hidden-line or hidden- surface elimination have been developed to solve this everyday problem that our visual system performs "at a glance". In contrast to the problems discussed above, visibility is surprisingly complex. We give a hint of this complexity by describing some of the details buried below the smooth surface of a "simple" version: computing the visibility of line segments in the plane. Problem: Given n line segments in the plane, compute the sequence of (sub)segments seen by an observer at infinity (say, at y = –∞). 279
algorithms and data structures_Page_279_Chunk4819
This book is licensed under a Creative Commons Attribution 3.0 License The complexity of this problem was unexpected until discovered in 1986 [WS 88]. Fortunately, this complexity is revealed not by requiring complicated algorithms, but in the analysis of the inherent complexity of the geometric problem. The example shown in Exhibit 24.11 illustrates the input data. The endpoints (P1, P10), (P2, P8), (P5, P12) of the three line segments labeled 1, 2, 3 are given; other points are computed by the algorithm. The required result is a list of visible segments, each segment described by its endpoints and by the identifier of the line of which it is a part: (P1, P3, 1), (P3, P4, 2), (P5, P6, 3), (P6, P8, 2), (P7, P9, 3), (P9, P10, 1), (P11, P12, 3) Exhibit 24.11: Example: Three line segments seen from below generate seven visible subsegments. In search of algorithms, the reader is encouraged to work out the details of the first idea that might come to mind: For each of the n2 ordered pairs (Li, Lj) of line segments, remove from Li the subsegment occluded by Lj. Because Li can get cut into as many as n pieces, it must be managed as a sequence of subsegments. Finding the endpoints of Lj in this sequence will take time O(log n), leading to an overall algorithm of time complexity O(n2 · log n). After the reader has mastered the sweep algorithm for line intersection presented in “Plane-sweep: a general- purpose algorithm for two-dimensional problems illustrated using line segment intersection”, he will see that its straightforward application to the line visibility problem requires time O((n + k) · log n), where k ∈ O(n2) is the number of intersections. Thus plane-sweep appears to do all the work the brute-force algorithm above does, organized in a systematic left-to-right fashion. It keeps track of all intersections, most of which may be invisible. It has the potential to work in time O(n · log n) for many realistic data configurations characterized by k ∈ O(n), but not in the worst case. Divide-and-conquer yields a simple two-dimensional visibility algorithm with a better worst-case performance. If n = 0 or 1, the problem is trivial. If n > 1, partition the set of n line segments into two (approximate) halves, solve both subproblems, and merge the results. There is no constraint on how the set is halved, so the divide step is easy. The conquer step is taken care of by recursion. Merging amounts to computing the minimum of two piecewise (not necessarily continuous) linear functions, in time linear in the number of pieces. The example with n = 4 shown in Exhibit 24.12 illustrates the algorithm. f12 is the visible front of segments 1 and 2, f34 of segments 3 and 4, min(f12, f34) of all four segments (Exhibit 24.13). Algorithms and Data Structures 280 A Global Text
algorithms and data structures_Page_280_Chunk4820
24. Sample problems and algorithms Exhibit 24.12: The four line segments will be partitioned into subsets {1, 2} and {3, 4}. Exhibit 24.13: The min operation merges the solutions of this divide-and-conquer algorithm. The time complexity of this divide-and-conquer algorithm is obtained as follows. Given that at each level of recursion the relevant sets of line segments can be partitioned into (approximate) halves, the depth of recursion is O(log n). A merge step that processes v visible subsegments takes linear time O(v). Together, all the merge steps at 281
algorithms and data structures_Page_281_Chunk4821
This book is licensed under a Creative Commons Attribution 3.0 License a given depth process at most V subsegments, where V is the total number of visible subsegments. Thus the total time is bounded by O(V · log n). How large can V be? Surprising theoretical results Let V(n) be the number of visible subsegments in a given configuration of n lines, i.e. the size of the output of the visibility computation. For tiny n, the worst cases [V(2) = 4, V(3) = 8] are shown in Exhibit 24.14. An attempt to find worst-case configurations for general n leads to examples such as that shown in Figure 24.15, with V(n) = 5·n – 8. Exhibit 24.14: Configurations with the largest number of visible subsegments. Figure 24.15: A family of configurations with 5·n – 8 visible subsegments. You will find it difficult to come up with a class of configurations for which V(n) grows faster. It is tempting to conjecture that V(n) ∈ O(n), but this conjecture is very hard to prove - for the good reason that it is false, as was discovered in [WS 88]. It turns out that V(n) ∈ Θ(n · α(n)), where α(n), the inverse of Ackermann's function (see “Computability and complexity”, Exercise 2), is a monotonically increasing function that grows so slowly that for practical purposes it can be treated as a constant, call it α. Let us present some of the steps of how this surprising result was arrived at. Occasionally, simple geometric problems can be tied to deep results in other branches of mathematics. We transform the two-dimensional visibility problem into a combinatorial string problem. By numbering the given line segments, walking along the x-axis from Algorithms and Data Structures 282 A Global Text
algorithms and data structures_Page_282_Chunk4822
24. Sample problems and algorithms left to right, and writing down the number of the line segment that is currently visible, we obtain a sequence of numbers (Exhibit 24.16). Exhibit 24.16: The Davenport-Schinzel sequence associated with a configuration of segments. A geometric configuration gives rise to a sequence u1, u2, … , um with the following properties: 1. 1 ≤ ui ≤ n for 1 ≤ i ≤ m (numbers identify line segments). 2. ui ≠ ui+1 for 1 ≤ i ≤ m – 1 (no two consecutive numbers are equal). 3. There are no five indices 1 ≤ a < b < c < d < e ≤ m such that ua = uc = ue = r and ub = ud = s, r ≠ s. This condition captures the geometric properties of two intersecting straight lines: If we ever see r, s, r, s (possibly separated), we will never see r again, as this would imply that r and s intersect more than once (Exhibit 24.17). Exhibit 24.17: The subsequence r, s, r, s excludes further occurrences of r. Example The sequence for the example above that shows m ≥ 5 n – 8 is 1, 2, 1, 3, 1, … , 1, n–1, 1, n–1, n–2, n–3, … , 3, 2, n, 2, n, 3, n, … , n, n–2, n, n–1, n. 283
algorithms and data structures_Page_283_Chunk4823
This book is licensed under a Creative Commons Attribution 3.0 License Sequences with the properties 1 to 3, called Davenport-Schinzel sequences, have been studied in the context of linear differential equations. The maximal length of a Davenport-Schinzel sequence is k · n · α(n), where k is a constant and α(n) is the inverse of Ackermann's function (see “Computability and complexity”, Exercise 2) [HS 86]. With increasing n, α(n) approaches infinity, albeit very slowly. This dampens the hope for a linear upper bound for the visibility problem, but does not yet disprove the conjecture. For the latter, we need an inverse: For any given Davenport-Schinzel sequence there exists a corresponding geometric configuration which yields this sequence. An explicit construction is given in [WS 88]. This establishes an isomorphism between the two-dimensional visibility problem and the Davenport-Schinzel sequences, and shows that the size of the output of the two-dimensional visibility problem can be superlinear - a result that challenges our geometric intuition. Exercises 1. Given a set of points S, prove that the pair of points farthest from each other must be vertices of the convex hull H(S). 2. Assume a model of computation in which the operations addition, multiplication, and comparison are available at unit cost. Prove that in such a model Ω(n · log n) is a lower bound for computing, in order, the vertices of the convex hull H(S) of a set S of n points. Hint: Show that every algorithm which computes the convex hull of n given points can be used to sort n numbers. 3. Complete the second algorithm for the point-in-polygon test in chapter 24 in the section “The uses of convexity: basic operations on polygons” which computes the crossing number of the polygon G around point P by addressing the special cases that arise when the semi-infinite ray R emanating from P intersects a vertex of G or overlaps an edge of G. 4. Consider an arbitrary (not necessarily simple) polygon G (Exhibit 24.18). Provide an interpretation for the winding number w(G, P) of G around an arbitrary point P not on G, and prove that w(G, P) / 2·π of P is always equal to the crossing number of P with respect to any ray R emanating from P. Exhibit 24.18: Winding number and crossing number of a polygon G with respect to P. 5. Design an algorithm that computes the area of an n-vertex simple, but not necessarily convex polygon in Θ(n) time. 6. We consider the problem of computing the intersection of two convex polygons which are given by their lists of vertices in cyclic order. (a) Show that the intersection is again a convex polygon. (b) Design an algorithm that computes the intersection. What is the time complexity of your algorithm? Algorithms and Data Structures 284 A Global Text
algorithms and data structures_Page_284_Chunk4824
24. Sample problems and algorithms 7. Intersection test for line L and [convex] polygon Q If an (infinitely extended) line L intersects a polygon Q, it must intersect one of Q's edges. Thus a test for intersection of a given line L with a polygon can be reduced to repeated test of L for intersection with [some of] Q's edges. (a) Prove that, in general, a test for line-polygon intersection must check at least n – 2 of Q's edges. Hint: Use an adversary argument. If two edges remain unchecked, they could be moved so as to invalidate the answer. (b) Design a test that works in time O(log n) for decoding whether a line L intersects a convex polygon Q. 8. Divide-and-conquer algorithms may divide the space in which the data is embedded, rather than the set of data (the set of lines). Describe an algorithm for computing the sequence of visible segments that partitions the space recursively into vertical stripes, until each stripe is "simple enough"; describe how you choose the boundaries of the stripes; state advantages and disadvantages of this algorithm as compared to the one described in chapter 24 in the section “Visibility in the plane: a simple algorithm whose analysis is not”. Analyze the asymptotic time complexity of this algorithm. 285
algorithms and data structures_Page_285_Chunk4825
This book is licensed under a Creative Commons Attribution 3.0 License 25. Plane-sweep: a general- purpose algorithm for two- dimensional problems illustrated using line segment intersection Learning objectives: • line segment intersection test • turning space dimensions into time dimensions • updating a y table and detecting intersections • sweeping across and intersection Plane-sweep is an algorithm schema for two-dimensional geometry of great generality and effectiveness, and algorithm designers are well advised to try it first. It works for a surprisingly large set of problems, and when it works, tends to be very efficient. Plane-sweep is easiest to understand under the assumption of nondegenerate configurations. After explaining plane-sweep under this assumption, we remark on how degenerate cases can be handled with plane-sweep. The line segment intersection test We present a plane-sweep algorithm [SH 76] for the line segment intersection test: Given n line segments in the plane, determine whether any two intersect; and if so, compute a witness (i.e. a pair of segments that intersect). Bounds on the complexity of this problem are easily obtained. The literature on computational geometry (e.g. [PS 85]) proves a lower bound Ω(n · log n). The obvious brute force approach of testing all n · (n – 1) / 2 pairs of line segments requires Θ(n2) time. This wide gap between n · log n and n2 is a challenge to the algorithm designer, who strives for an optimal algorithm whose asymptotic running time O(n · log n) matches the lower bound. Divide-and-conquer is often the first attempt to design an algorithm, and it comes in two variants illustrated in Fig. 25.1: (1) Divide the data, in this case the set of line segments, into two subsets of approximately equal size (i.e. n / 2 line segments), or (2) divide the embedding space, which is easily cut in exact halves. Algorithms and Data Structures 286 A Global Text
algorithms and data structures_Page_286_Chunk4826
25. Plane-sweep: a general-purpose algorithm for two-dimensional problems illustrated using line segment intersection Exhibit 25.1: Two ways of applying divide-and-conquer to a set of objects embedded in the plane. In the first case, we hope for a separation into subsets S1 and S2 that permits an efficient test whether any line segment in S1 intersects some line segment in S2. Exhibit 25.1 shows the ideal case where S1 and S2 do not interact, but of course this cannot always be achieved in a nontrivial way; and even if S can be separated as the figure suggests, finding such a separating line looks like a more formidable problem than the original intersection problem. Thus, in general, we have to test each line segment in S1 against every line segment in S2, a test that may take Θ(n2) time. The second approach of dividing the embedding space has the unfortunate consequence of effectively increasing our data set. Every segment that straddles the dividing line gets "cut" (i.e. processed twice, once for each half space). The two resulting subproblems will be of size n' and n", respectively, with n' + n" > n, in the worst case n' + n" = 2 · n. At recursion depth d we may have 2d · n subsegments to process. No optimal algorithm is known that uses this technique. The key idea in designing an optimal algorithm is the observation that those line segments that intersect a vertical line L at abscissa x are totally ordered: A segment s lies below segment t, written s <L t, if both intersect L at the current position x and the intersection of s with L lies below the intersection of t with L. With respect to this order a line segment may have an upper and a lower neighbor, and Exhibit 25.2 shows that s and t are neighbors at x. Exhibit 25.2: The sweep line L totally orders the segments that intersect L. We describe the intersection test algorithm under the assumption that the configuration is nondegenerate (i.e. no three segments intersect in the same point). For simplicity's sake we also assume that no segment is vertical, so every segment has a left endpoint and a right endpoint. The latter assumption entails no loss of generality: For a vertical segment, we can arbitrarily define the lower endpoint to be the "left endpoint", thus imposing a lexicographic (x, y)-order to refine the x-order. With the important assumption of non-degeneracy, two line segments s and t can intersect at x0 only if there exists an abscissa x < x0 where s and t are neighbors. Thus it 287
algorithms and data structures_Page_287_Chunk4827
This book is licensed under a Creative Commons Attribution 3.0 License suffices to test all segment pairs that become neighbors at some time during a left-to-right sweep of L - a number that is usually significantly smaller than n · (n – 1) / 2. As the sweep line L moves from left to right across the configuration, the order < L among the line segments intersecting L changes only at endpoints of a segment or at intersections of segments. As we intend to stop the sweep as soon as we discover an intersection, we need to perform the intersection test only at the left and right endpoints of segments. A segment t is tested at its left endpoint for intersection with its lower and upper neighbors. At the right endpoint of t we test its lower and upper neighbor for intersection (Exhibit 25.3). The algorithm terminates as soon as we discover an intersecting pair of segments. Given n segments, each of Exhibit 25.3: Three pairwise intersection tests charged to segment t. which may generate three intersection tests as shown in Exhibit 25.3 (two at its left, one at its right endpoint), we perform the O(1) pairwise segment intersection test at most 3 · n times. This linear bound on the number of pairs tested for intersection might raise the hope of finding a linear-time algorithm, but so far we have counted only the geometric primitive: "Does a pair of segments intersect - yes or no?" Hiding in the background we find bookkeeping operations such as "Find the upper and lower neighbor of a given segment", and these turn out to be costlier than the geometric ones. We will find neighbors efficiently by maintaining the order <L in a data structure called a y- table during the entire sweep. The skeleton: Turning a space dimension into a time dimension The name plane-sweep is derived from the image of sweeping the plane from left to right with a vertical line (front, or cross section), stopping at every transition point (event) of a geometric configuration to update the cross section. All processing is done at this moving front, without any backtracking, with a look-ahead of only one point. The events are stored in the x-queue, and the current cross section is maintained by the y-table. The skeleton of a plane-sweep algorithm is as follows: initX; initY; while not emptyX do { e := nextX; transition(e) } The procedures 'initX' and 'initY' initialize the x-queue and the y-table. 'nextX' returns the next event in the x- queue, 'emptyX' tells us whether the x-queue is empty. The procedure 'transition', the advancing mechanism of the sweep, embodies all the work to be done when a new event is encountered; it moves the front from the slice to the left of an event e to the slice immediately to the right of e. Data structures For the line segment intersection test, the x-queue stores the left and right endpoints of the given line segments, ordered by their x-coordinate, as events to be processed when updating the vertical cross section. Each endpoint stores a reference to the corresponding line segment. We compare points by their x-coordinates when building the Algorithms and Data Structures 288 A Global Text
algorithms and data structures_Page_288_Chunk4828
25. Plane-sweep: a general-purpose algorithm for two-dimensional problems illustrated using line segment intersection x-queue. For simplicity of presentation we assume that no two endpoints of line segments have equal x- or y- coordinates. The only operation to be performed on the x-queue is 'nextX': it returns the next event (i.e. the next left or right endpoint of a line segment to be processed). The cost for initializing the x-queue is O(n · log n), the cost for performing the 'nextX' operation is O(1). The y-table contains those line segments that are currently intersected by the sweep line, ordered according to <L. In the slice between two events, this order does not change, and the y-table needs no updating (Exhibit 25.4). The y-table is a dictionary that supports the operations 'insertY', 'deleteY', 'succY', and 'predY'. When entering the left endpoint of a line segment s we find the place where s is to be inserted in the ordering of the y-table by comparing s to other line segments t already stored in the y-table. We can determine whether s <L t or t <L s by determining on which side of t the left endpoint of s lies. As we have seen in chapter 14 in the section “Intersection”, this tends to be more efficient than computing and comparing the intersection points of s and t with the sweep line. If we implement the dictionary as a balanced tree (e.g. an AVL tree), the operations 'insertY' and 'deleteY' are performed in O(log n) time, and 'succY' and 'predY' are performed in O(1) time if additional pointers in each node of the tree point to the successor and predecessor of the line segment stored in this node. Since there are 2 · n events in the x-queue and at most n line segments in the y-table the space complexity of this plane-sweep algorithm is O(n). Exhibit 25.4: The y-table records the varying state of the sweep line L. Updating the y-table and detecting an intersection The procedure 'transition' maintains the order <L of the line segments intersecting the sweep line and performs intersection tests. At a left endpoint of a segment t, t is inserted into the y-table and tested for intersection with its lower and upper neighbors. At the right endpoint of t, t is deleted from the y-table and its two former neighbors are tested. The algorithm terminates when an intersection has been found or all events in the x-queue have been processed without finding an intersection: procedure transition(e: event); begin s := segment(e); if leftPoint(e) then begin insertY(s); 289
algorithms and data structures_Page_289_Chunk4829
This book is licensed under a Creative Commons Attribution 3.0 License if intersect(predY(s), s) or intersect (s, succY(s)) then terminate('intersection found') end else { e is right endpoint of s } begin if intersect(predY(s), succY(s)) then terminate('intersection found'); deleteY(s) end end; With at most 2 · n events, and a call of 'transition' costing time O(log n), this plane-sweep algorithm needs O(n · log n) time to perform the line segment intersection test. Sweeping across intersections The plane-sweep algorithm for the line segment intersection test is easily adapted to the following more general problem [BO 79]: Given n line segments, report all intersections. In addition to the left and right endpoints, the x-queue now stores intersection points as events—any intersection detected is inserted into the x-queue as an event to be processed. When the sweep line reaches an intersection event the two participating line segments are swapped in the y-table (Exhibit 25.5). The major increase in complexity as compared to the segment intersection test is that now we must process not only 2 · n events, but 2 · n + k events, where k is the number of intersections discovered as we sweep the plane. A configuration with n / 2 segments vertical and n / 2 horizontal shows that, in the worst case, k ∈ Θ(n2), which leads to an O(n2 · log n) algorithm, certainly no improvement over the brute-force comparison of all pairs. In most realistic configurations, say engineering drawings, the number of intersections is much less than O(n2), and thus it is informative to introduce the parameter k in order to get an output-sensitive bound on the complexity of this algorithm (i.e. a bound that adapts to the amount of data needed to report the result of the computation). Exhibit 25.5: Sweeping across an intersection. Other changes are comparatively minor. The x-queue must be a priority queue that supports the operation 'insertX'; it can be implemented as a heap. The cost for initializing the x-queue remains O(n · log n). Without further analysis one might presume that the storage requirement of the x-queue is O(n + k), which implies that the cost for calling 'insertX' and 'nextX' remains O(log n), since k ∈ O(n2). A more detailed analysis [PS 91], however, shows that the size of the x-queue never exceeds O(n · (log n)2). With a slight modification of the algorithm [Bro 81] Algorithms and Data Structures 290 A Global Text
algorithms and data structures_Page_290_Chunk4830
25. Plane-sweep: a general-purpose algorithm for two-dimensional problems illustrated using line segment intersection it can even be guaranteed that the size of the x-queue never exceeds O(n). The cost for exchanging two intersecting line segments in the y-table is O(log n), the costs for the other operations on the y-table remain the same. Since there are 2 · n left and right endpoints and k intersection events, the total cost for this algorithm is O((n + k) · log n). As most realistic applications are characterized by k ∈ O(n), reporting all intersections often remains an O(n · log n) algorithm in practice. A time-optimal algorithm that finds all intersecting pairs of line segments in O(n · log n + k) time using O(n + k) storage space is described in [CE 92]. Degenerate configurations, numerical errors, robustness The discussion above is based on several assumptions of nondegeneracy, some of minor and some of major importance. Let us examine one of each type. Whenever we access the x-queue ('nextX'), we used an implicit assumption that no two events (endpoints or intersections) have equal x-coordinates. The order of processing events of equal x-coordinate is irrelevant. Assuming that no two events coincide at the same point in the plane, lexicographic (x, y)-ordering is a convenient systematic way to define 'nextX'. More serious forms of degeneracy arise when events coincide in the plane, such as more than two segments intersecting in the same point. This type of degeneracy is particularly difficult to handle in the presence of numerical errors, such as rounding errors. In the configuration shown in Exhibit 25.6 an endpoint of u lies exactly or nearly on segment s. We may not care whether the intersection routine answers 'yes' or 'no' to the question "Do s and u intersect?" but we certainly expect a 'yes' when asking "Do t and u intersect?" This example shows that the slightest numerical inaccuracy can cause a serious error: The algorithm may fail to report the intersection of t and u, which it would clearly see if it bothered to look - but the algorithm looks the other way and never asks the question "Do t and u intersect?" Exhibit 25.6: A degenerate configuration may lead to inconsistent results. The trace of the plane-sweep for reporting intersections may look as follows: 1. s is inserted into the y-table 2. t is inserted above s into the y-table, and s and t are tested for intersection: No intersection is found 3. u is inserted below s in the y-table (since the evaluation of the function s(x) may conclude that the left endpoint of u lies below s); s and u are tested for intersection, but the intersection routine may conclude that s and u do not intersect: u remains below s 291
algorithms and data structures_Page_291_Chunk4831
This book is licensed under a Creative Commons Attribution 3.0 License 4. Delete u from the y-table 5. Delete s from the y-table 6. Delete t from the y-table Notice the calamity that struck at the critical step 3. The evaluation of a linear expression s(x) and the intersection routine for two segments both arrived at a result that, in isolation, is reasonable within the tolerance of the underlying arithmetic. The two results together are inconsistent! If the evaluation of s(x) concludes that the left endpoint of u lies below s, the intersection routine must conclude that s and u intersect! If these two geometric primitives fail to coordinate their answers, catastrophe may strike. In our example, u and t never become neighbors in the y-table, so their intersection gets lost. Exercises 1. Show that there may be Θ(n2) intersections in a set of n line segments. 2. Design a plane-sweep algorithm that determines in O(n · log n) time whether two simple polygons with a total of n vertices intersect. 3. Design a plane-sweep algorithm that determines in O(n · log n) time whether any two disks in a set of n disks intersect. 4. Design a plane-sweep algorithm that solves the line visibility problem discussed in chapter 24 in the section “Visibility in the plane: a simple algorithm whose analysis is not” in time O((n + k) · log n), where k ∈ O(n2) is the number of intersections of the line segments. 5. Give a configuration with the smallest possible number of line segments for which the first intersection point reported by the plane-sweep algorithm in chapter 25 in the section “Sweeping across intersections” is not the leftmost intersection point. 6. Adapt the plane-sweep algorithm presented in chapter 25 in the section “Sweeping across intersections” to detect all intersections among a given set of n horizontal or vertical line segments. You may assume that the line segments do not overlap. What is the time complexity of this algorithm if the horizontal and vertical line segments intersect in k points? 7. Design a plane-sweep algorithm that finds all intersections among a given set of n rectangles all of whose sides are parallel to the coordinate axes. What is the time complexity of your algorithm? Algorithms and Data Structures 292 A Global Text
algorithms and data structures_Page_292_Chunk4832
26. The closest pair 26. The closest pair Learning objectives: • Applying, implementing and analyzing plane sweep • Using plane sweep on three or more dimensions Sweep algorithms solve many kinds of proximity problems efficiently. We present a simple sweep that solves the two-dimensional closest pair problem elegantly in asymptotically optimal time. We explain why sweeping generalizes easily, but not efficiently, to multidimensional closest pair problems. The problem We consider the two-dimensional closest pair problem: Given a set S of n points in the plane find a pair of points whose distance δ is smallest (Exhibit 26.1). We measure distance using the metric dk, for any k ≥ 1, or d∞, defined as: Exhibit 26.1: Identify a closest pair among n points in the plane. Special cases of interest include the "Manhattan metric" d1, the "Euclidean metric" d2, and the "maximum metric" d∞. Exhibit 26.2 shows the "circles" of radius 1 centered at a point p for some of these metrics. Exhibit 26.2: The results of this chapter remain valid when distances are measured in various metrics. The closest pair problem has a lower bound Ω(n · log n) in the algebraic decision tree model of computation [PS 85]. Its solution can be obtained in asymptotically optimal time O(n · log n) as a special case of more general problems, such as 'all-nearest-neighbors' [HNS 92] (for each point, find a nearest neighbor), or constructing the Voronoi diagram [SH 75]. These general approaches call on powerful techniques that make the resulting algorithms harder to understand than one would expect for a simply stated problem such as "find a closest pair". The divide- and-conquer algorithm presented in [BS 76] solves the closest pair problem directly in optimal worst-case time complexity Θ(n · log n) using the Euclidean metric d2. Whereas the recursive divide-and-conquer algorithm 293
algorithms and data structures_Page_293_Chunk4833
This book is licensed under a Creative Commons Attribution 3.0 License involves an intricate argument for combining the solutions of two equally sized subsets, the iterative plane-sweep algorithm [HNS 88] uses a simple incremental update: Starting with the empty set of points, keep adding a single point until the final solution for the entire set is obtained. A similar plane-sweep algorithm solves the closest pair problem for a set of convex objects [BH 92]. Plane-sweep applied to the closest pair problem The skeleton of the general sweep algorithm presented in chapter 25 in the section “The skeleton: turning a space dimension into a time dimension”, with the data structures x-queue and y-table, is adapted to the closest pair problem as shown in Exhibit 26.3. The x-queue stores the points of the set S, ordered by their x-coordinate, as events to be processed when updating the vertical cross section. Two pointers into the x-queue, 'tail' and 'current', partition S into four disjoint subsets: 1. The discarded points to the left of 'tail' are not accessed any longer 2. The active points between 'tail' (inclusive) and 'current' (exclusive) are being queried 3. The current transition point, p, is being processed 4. The future points have not yet been looked at The y-table stores the active points only, ordered by their y-coordinate. Exhibit 26.3: Updating the invariant as the next point p is processed. We need to compare points by their x-coordinates when building the x-queue, and by their y-coordinates while sweeping. For simplicity of presentation we assume that no two points have equal x- or y-coordinates. Points with equal x- or y-coordinates are handled by imposing an arbitrary, but consistent, total order on the set of points. We achieve this by defining two lexicographic orders: <x to be used for the x-queue, <y for the y-table: Algorithms and Data Structures 294 A Global Text
algorithms and data structures_Page_294_Chunk4834
26. The closest pair The program of the following section initializes the x-queue and y-table with the two leftmost points being active, with δ equal to their distance, and starts the sweep with the third point. The distinction between discarded and active points is motivated by the following argument. When a new point p is encountered we wish to answer the question whether this point forms a closest pair with one of the points to its left. We keep a pair of closest points seen so far, along with the corresponding minimal distance δ. Therefore, all candidates that may form a new closest pair with the point p on the sweep line lie in a half circle centered at p, with radius δ. The key question to be answered in striving for efficiency is how to retrieve quickly all the points seen so far that lie inside this half circle to the left of p, in order to compare their distance to p against the minimal distance δ seen so far. We may use any helpful data structure that organizes the points seen so far, as long as we can update this data structure efficiently across a transition. A circle (or half-circle) query is complex, at least when embedded in a plane-sweep algorithm that organizes data according to an orthogonal coordinate system. A rectangle query can be answered more efficiently. Thus we replace the half-circle query with a bounding rectangle query, accepting the fact that we might include some extraneous points, such as q. The rectangle query in Exhibit 26.3 is implemented in two steps. First, we cut off all the points to the left at distance ≥ δ from the sweep line. These points lie between 'tail' and 'current' in the x-queue and can be discarded easily by advancing 'tail' and removing them from the y-table. Second, we consider only those points q in the δ-slice whose vertical distance from p is less than δ: |qy – py| < δ. These points can be found in the y-table by looking at successors and predecessors starting at the y-coordinate of p. In other words, we maintain the following invariant across a transition: 1. δ is the minimal distance between a pair of points seen so far (discarded or active). 2. The active points (found in the x-queue between 'tail' and 'current', and stored in the y-table ordered by y- coordinates) are exactly those that lie in the interior of a δ-slice to the left of the sweep line. 3. Therefore, processing the transition point p involves three steps: 4. Delete all points q with qx ≤ px – δfrom the y-table. They are found by advancing 'tail' to the right. 5. Insert p into the y-table. 6. Find all points q in the y-table with |qy – py| < δ by looking at the successors and predecessors of p. If such a point q is found and its distance from p is smaller than δ, update δ and the closest pair found so far. Implementation In the following implementation the x-queue is realized by an array that contains all the points sorted by their x- coordinate. 'closestLeft' and 'closestRight' describe the pair of closest points found so far, n is the number of points under consideration, and t and c determine the positions of 'tail' and 'current': xQueue: array[1 .. maxN] of point; closestLeft, closestRight: point; t, c, n: 1 .. maxN; 295
algorithms and data structures_Page_295_Chunk4835
This book is licensed under a Creative Commons Attribution 3.0 License The x-queue is initialized by procedure initX; 'initX' stores all the points into the x-queue, ordered by their x- coordinates. The empty y-table is created by procedure initY; A new point is inserted into the y-table by procedure insertY(p: point); A point is deleted from the y-table by procedure deleteY(p: point); The successor of a point in the y-table is returned by function succY(p: point): point; The predecessor of a point in the y-table is returned by function predY(p: point): point; The initialization part of the plane-sweep is as follows: initX; initY; closestLeft := xQueue[1]; closestRight := xQueue[2]; delta := distance(closestLeft, closestRight); insertY(closestLeft); insertY(closestRight); c := 3; The events are processed by the loop: while c ≤ n do begin transition; c := c + 1; { next event } end; The procedure 'transition' encompasses all the work to be done for a new point: procedure transition; begin { step 1: remove points outside the δ-slice from the y-table } current := xQueue[c]; while current.x – xQueue[t].x ≥ delta do begin deleteY(xQueue[t]); t := t + 1 end; { step 2: insert the new point into the y-table } insertY(current); { step 3a: check the successors of the new point in the y-table } check := current; repeat check := succY(check); newDelta := distance(current, check); if newDelta < delta then begin delta := newDelta; closestLeft := check; closestRight := current; end; until check.y – current.y > delta; { step 3b: check the predecessors of the new point in the y- table } check := current; repeat check := predY(check); newDelta := distance(current, check); Algorithms and Data Structures 296 A Global Text
algorithms and data structures_Page_296_Chunk4836
26. The closest pair if newDelta < delta then begin delta := newDelta; closestLeft := check; closestRight := current; end; until current.y – check.y > delta; end; { transition } Analysis We show that the algorithm described can be implemented so as to run in worst-case time O(n · log n) and space O(n). If the y-table is implemented by a balanced binary tree (e.g. an AVL-tree or a 2-3-tree) the operations 'insertY', 'deleteY', 'succY', and 'predY' can be performed in time O(log n). The space required is O(n). 'initX' builds the sorted x-queue in time O(n · log n) using space O(n). The procedure 'deleteY' is called at most once for each point and thus accumulates to O(n · log n). Every point is inserted once into the y-table, thus the calls of 'insertY' accumulate to O(n · log n). There remains the problem of analyzing step 3. The loop in step 3a calls 'succY' once more than the number of points in the upper half of the bounding box. Similarly, the loop in step 3b calls 'predY' once more than the number of points in the lower half of the bounding box. A standard counting technique shows that the bounding box is sparsely populated: For any metric dk, the box contains no more than a small, constant number ck of points, and for any k, ck ≤ 8. Thus 'succY' and 'predY' are called no more than 10 times, and step 3 costs time O(log n). The key to this counting is the fact that no two points in the y-table can be closer than δ, and thus not many of them can be packed into the bounding box with sides δ and 2 · δ. We partition this box into the eight pairwise disjoint, mutually exhaustive regions shown in Exhibit 26.4. These regions are half circles of diameter δ in the Manhattan metric d1, and we first argue our case only when distances are measured in this metric. None of these half-circles can contain more than one point. If a half-circle contained two points at distance δ, they would have to be at opposite ends of the unique diameter of this half-circle. These endpoints lie on the left or the right boundary of the bounding box, and these two boundary lines cannot contain any points, for the following reasons: • No active point can be located on the left boundary of the bounding box; such a point would have been thrown out when the δ-slice was last updated. • No active point can exist on the right boundary, as that x-coordinate is preempted by the transition point p being processed (remember our assumption of unequal x-coordinates). 297
algorithms and data structures_Page_297_Chunk4837
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 26.4: Only few points at pairwise distance ≥ δ can populate a box of size 2 · δ by δ. We have shown that the bounding box can hold no more than eight points at pairwise distance ≥ δ when using the Manhattan metric d1. It is well known that for any points p, q, and for any k > 1: d1(p,q) > dk(p,q) > d∞(p,q). Thus the bounding box can hold no more than eight points at pairwise distance ≥ δ when using any distance dk or d∞. Therefore, the calculation of the predecessors and successors of a transition point costs time O(log n) and accumulates to a total of O(n · log n) for all transitions. Summing up all costs results in O(n · log n) time and O(n) space complexity for this algorithm. Since Ω(n · log n) is a lower bound for the closest pair problem, we know that this algorithm is optimal. Sweeping in three or more dimensions To gain insight into the power and limitation of sweep algorithms, let us explore whether the algorithm presented generalizes to higher-dimensional spaces. We illustrate our reasoning for three-dimensional space, but the same conclusion holds for any number of dimensions > 2. All of the following steps generalize easily. Sort all the points according to their x-coordinate into the x-queue. Sweep space with a y-z plane, and in processing the current transition point p, assume that we know the closest pair among all the points to the left of p, and their distance δ. Then to determine whether p forms a new closest pair, look at all the points inside a half- sphere of radius δ centered at p, extending to the left of p. In the hope of implementing this sphere query efficiently, we enclose this half sphere in a bounding box of side length 2 · δ in the y- and z-dimension, and δ in the x- dimension. Inside this box there can be at most a small, constant number ck of points at pairwise distance ≥ δ when using any distance dk or d∞. We implement this box query in two steps: (1) by cutting off all the points farther to the left of p than δ, which is done by advancing 'tail' in the x-queue, and (2) by performing a square query among the points currently in the y-z- table (which all lie in the δ-slice to the left of the sweep plane), as shown in Exhibit 26.5. Now we have reached the only place where the three-dimensional algorithm differs substantially. In the two-dimensional case, the corresponding one-dimensional interval query can be implemented efficiently in time O(log n) using find, predecessor, and successor operations on a balanced tree, and using the knowledge that the size of the answer set is Algorithms and Data Structures 298 A Global Text
algorithms and data structures_Page_298_Chunk4838
26. The closest pair bounded by a constant. In the three-dimensional case, the corresponding two-dimensional orthogonal range query cannot in general be answered in time O(log n) (per retrieved point) using any of the known data structures. Straightforward search requires time O(n), resulting in an overall time O(n2) for the space sweep. This is not an interesting result for a problem that admits the trivial O(n2) algorithm of comparing every pair. Exhibit 26.5: Sweeping a plane across three-dimensional space. Ideas generalize, but efficiency does not. Sweeping reduces the dimensionality of a geometric problem by one, by replacing one space dimension by a "time dimension". Reducing a two-dimensional problem to a sequence of one-dimensional problems is often efficient because the total order defined in one dimension allows logarithmic search times. In contrast, reducing a three-dimensional problem to a sequence of two-dimensional problems rarely results in a gain in efficiency. Exercises 1. Consider the following modification of the plane-sweep algorithm for solving the closest pair problem [BH 92]. When encountering a transition point p do not process all points q in the y-table with |q y – py| < δ, but test only whether the distance of p to its successor or predecessor in the y-table is smaller than δ. When deleting a point q with qx ≤ px – δ from the y-table test whether the successor and predecessor of q in the y- table are closer than δ. If a pair of points with a smaller distance than the current δ is found update δ and the closest pair found so far. Prove that this modified algorithm finds a closest pair What is the time complexity of this algorithm? 2. Design a divide-and-conquer algorithm which solves the closest pair problem. What is the time complexity of your algorithm? Hint: Partition the set of n points by a vertical line into two subsets of approximately n / 2 points. Solve the closest pair problem recursively for both subsets. In the conquer step you should use the fact that δ is the smallest distance between any pair of points both belonging to the same subset. A point from the left subset can only have a distance smaller than δ to a point in the right subset if both points lie in a 2 · δ-slice to the left and to the right of the partitioning line. Therefore, you only have to match points lying in the left δ-slice against points lying in the right δ-slice. 299
algorithms and data structures_Page_299_Chunk4839
Grinstead and Snell’s Introduction to Probability The CHANCE Project1 Version dated 4 July 2006 1Copyright (C) 2006 Peter G. Doyle. This work is a version of Grinstead and Snell’s ‘Introduction to Probability, 2nd edition’, published by the American Mathematical So- ciety, Copyright (C) 2003 Charles M. Grinstead and J. Laurie Snell. This work is freely redistributable under the terms of the GNU Free Documentation License.
prob_Page_1_Chunk4840
To our wives and in memory of Reese T. Prosser
prob_Page_2_Chunk4841
Contents Preface vii 1 Discrete Probability Distributions 1 1.1 Simulation of Discrete Probabilities . . . . . . . . . . . . . . . . . . . 1 1.2 Discrete Probability Distributions . . . . . . . . . . . . . . . . . . . . 18 2 Continuous Probability Densities 41 2.1 Simulation of Continuous Probabilities . . . . . . . . . . . . . . . . . 41 2.2 Continuous Density Functions . . . . . . . . . . . . . . . . . . . . . . 55 3 Combinatorics 75 3.1 Permutations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 3.2 Combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 3.3 Card Shuffling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 4 Conditional Probability 133 4.1 Discrete Conditional Probability . . . . . . . . . . . . . . . . . . . . 133 4.2 Continuous Conditional Probability . . . . . . . . . . . . . . . . . . . 162 4.3 Paradoxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 5 Distributions and Densities 183 5.1 Important Distributions . . . . . . . . . . . . . . . . . . . . . . . . . 183 5.2 Important Densities . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 6 Expected Value and Variance 225 6.1 Expected Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 6.2 Variance of Discrete Random Variables . . . . . . . . . . . . . . . . . 257 6.3 Continuous Random Variables . . . . . . . . . . . . . . . . . . . . . . 268 7 Sums of Random Variables 285 7.1 Sums of Discrete Random Variables . . . . . . . . . . . . . . . . . . 285 7.2 Sums of Continuous Random Variables . . . . . . . . . . . . . . . . . 291 8 Law of Large Numbers 305 8.1 Discrete Random Variables . . . . . . . . . . . . . . . . . . . . . . . 305 8.2 Continuous Random Variables . . . . . . . . . . . . . . . . . . . . . . 316 v
prob_Page_3_Chunk4842
vi CONTENTS 9 Central Limit Theorem 325 9.1 Bernoulli Trials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 9.2 Discrete Independent Trials . . . . . . . . . . . . . . . . . . . . . . . 340 9.3 Continuous Independent Trials . . . . . . . . . . . . . . . . . . . . . 356 10 Generating Functions 365 10.1 Discrete Distributions . . . . . . . . . . . . . . . . . . . . . . . . . . 365 10.2 Branching Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 10.3 Continuous Densities . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 11 Markov Chains 405 11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405 11.2 Absorbing Markov Chains . . . . . . . . . . . . . . . . . . . . . . . . 416 11.3 Ergodic Markov Chains . . . . . . . . . . . . . . . . . . . . . . . . . 433 11.4 Fundamental Limit Theorem . . . . . . . . . . . . . . . . . . . . . . 447 11.5 Mean First Passage Time . . . . . . . . . . . . . . . . . . . . . . . . 452 12 Random Walks 471 12.1 Random Walks in Euclidean Space . . . . . . . . . . . . . . . . . . . 471 12.2 Gambler’s Ruin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486 12.3 Arc Sine Laws . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 Appendices 499 Index 503
prob_Page_4_Chunk4843
Preface Probability theory began in seventeenth century France when the two great French mathematicians, Blaise Pascal and Pierre de Fermat, corresponded over two prob- lems from games of chance. Problems like those Pascal and Fermat solved continued to influence such early researchers as Huygens, Bernoulli, and DeMoivre in estab- lishing a mathematical theory of probability. Today, probability theory is a well- established branch of mathematics that finds applications in every area of scholarly activity from music to physics, and in daily experience from weather prediction to predicting the risks of new medical treatments. This text is designed for an introductory probability course taken by sophomores, juniors, and seniors in mathematics, the physical and social sciences, engineering, and computer science. It presents a thorough treatment of probability ideas and techniques necessary for a firm understanding of the subject. The text can be used in a variety of course lengths, levels, and areas of emphasis. For use in a standard one-term course, in which both discrete and continuous probability is covered, students should have taken as a prerequisite two terms of calculus, including an introduction to multiple integrals. In order to cover Chap- ter 11, which contains material on Markov chains, some knowledge of matrix theory is necessary. The text can also be used in a discrete probability course. The material has been organized in such a way that the discrete and continuous probability discussions are presented in a separate, but parallel, manner. This organization dispels an overly rigorous or formal view of probability and offers some strong pedagogical value in that the discrete discussions can sometimes serve to motivate the more abstract continuous probability discussions. For use in a discrete probability course, students should have taken one term of calculus as a prerequisite. Very little computing background is assumed or necessary in order to obtain full benefits from the use of the computing material and examples in the text. All of the programs that are used in the text have been written in each of the languages TrueBASIC, Maple, and Mathematica. This book is distributed on the Web as part of the Chance Project, which is de- voted to providing materials for beginning courses in probability and statistics. The computer programs, solutions to the odd-numbered exercises, and current errata are also available at this site. Instructors may obtain all of the solutions by writing to either of the authors, at jlsnell@dartmouth.edu and cgrinst1@swarthmore.edu. vii
prob_Page_5_Chunk4844
viii PREFACE FEATURES Level of rigor and emphasis: Probability is a wonderfully intuitive and applicable field of mathematics. We have tried not to spoil its beauty by presenting too much formal mathematics. Rather, we have tried to develop the key ideas in a somewhat leisurely style, to provide a variety of interesting applications to probability, and to show some of the nonintuitive examples that make probability such a lively subject. Exercises: There are over 600 exercises in the text providing plenty of oppor- tunity for practicing skills and developing a sound understanding of the ideas. In the exercise sets are routine exercises to be done with and without the use of a computer and more theoretical exercises to improve the understanding of basic con- cepts. More difficult exercises are indicated by an asterisk. A solution manual for all of the exercises is available to instructors. Historical remarks: Introductory probability is a subject in which the funda- mental ideas are still closely tied to those of the founders of the subject. For this reason, there are numerous historical comments in the text, especially as they deal with the development of discrete probability. Pedagogical use of computer programs: Probability theory makes predictions about experiments whose outcomes depend upon chance. Consequently, it lends itself beautifully to the use of computers as a mathematical tool to simulate and analyze chance experiments. In the text the computer is utilized in several ways. First, it provides a labora- tory where chance experiments can be simulated and the students can get a feeling for the variety of such experiments. This use of the computer in probability has been already beautifully illustrated by William Feller in the second edition of his famous text An Introduction to Probability Theory and Its Applications (New York: Wiley, 1950). In the preface, Feller wrote about his treatment of fluctuation in coin tossing: “The results are so amazing and so at variance with common intuition that even sophisticated colleagues doubted that coins actually misbehave as theory predicts. The record of a simulated experiment is therefore included.” In addition to providing a laboratory for the student, the computer is a powerful aid in understanding basic results of probability theory. For example, the graphical illustration of the approximation of the standardized binomial distributions to the normal curve is a more convincing demonstration of the Central Limit Theorem than many of the formal proofs of this fundamental result. Finally, the computer allows the student to solve problems that do not lend themselves to closed-form formulas such as waiting times in queues. Indeed, the introduction of the computer changes the way in which we look at many problems in probability. For example, being able to calculate exact binomial probabilities for experiments up to 1000 trials changes the way we view the normal and Poisson approximations. ACKNOWLEDGMENTS Anyone writing a probability text today owes a great debt to William Feller, who taught us all how to make probability come alive as a subject matter. If you
prob_Page_6_Chunk4845
PREFACE ix find an example, an application, or an exercise that you really like, it probably had its origin in Feller’s classic text, An Introduction to Probability Theory and Its Applications. We are indebted to many people for their help in this undertaking. The approach to Markov Chains presented in the book was developed by John Kemeny and the second author. Reese Prosser was a silent co-author for the material on continuous probability in an earlier version of this book. Mark Kernighan contributed 40 pages of comments on the earlier edition. Many of these comments were very thought- provoking; in addition, they provided a student’s perspective on the book. Most of the major changes in this version of the book have their genesis in these notes. Fuxing Hou and Lee Nave provided extensive help with the typesetting and the figures. John Finn provided valuable pedagogical advice on the text and and the computer programs. Karl Knaub and Jessica Sklar are responsible for the implementations of the computer programs in Mathematica and Maple. Jessica and Gang Wang assisted with the solutions. Finally, we thank the American Mathematical Society, and in particular Sergei Gelfand and John Ewing, for their interest in this book; their help in its production; and their willingness to make the work freely redistributable.
prob_Page_7_Chunk4846
x PREFACE
prob_Page_8_Chunk4847
Chapter 1 Discrete Probability Distributions 1.1 Simulation of Discrete Probabilities Probability In this chapter, we shall first consider chance experiments with a finite number of possible outcomes ω1, ω2, . . . , ωn. For example, we roll a die and the possible outcomes are 1, 2, 3, 4, 5, 6 corresponding to the side that turns up. We toss a coin with possible outcomes H (heads) and T (tails). It is frequently useful to be able to refer to an outcome of an experiment. For example, we might want to write the mathematical expression which gives the sum of four rolls of a die. To do this, we could let Xi, i = 1, 2, 3, 4, represent the values of the outcomes of the four rolls, and then we could write the expression X1 + X2 + X3 + X4 for the sum of the four rolls. The Xi’s are called random variables. A random vari- able is simply an expression whose value is the outcome of a particular experiment. Just as in the case of other types of variables in mathematics, random variables can take on different values. Let X be the random variable which represents the roll of one die. We shall assign probabilities to the possible outcomes of this experiment. We do this by assigning to each outcome ωj a nonnegative number m(ωj) in such a way that m(ω1) + m(ω2) + · · · + m(ω6) = 1 . The function m(ωj) is called the distribution function of the random variable X. For the case of the roll of the die we would assign equal probabilities or probabilities 1/6 to each of the outcomes. With this assignment of probabilities, one could write P(X ≤4) = 2 3 1
prob_Page_9_Chunk4848
2 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS to mean that the probability is 2/3 that a roll of a die will have a value which does not exceed 4. Let Y be the random variable which represents the toss of a coin. In this case, there are two possible outcomes, which we can label as H and T. Unless we have reason to suspect that the coin comes up one way more often than the other way, it is natural to assign the probability of 1/2 to each of the two outcomes. In both of the above experiments, each outcome is assigned an equal probability. This would certainly not be the case in general. For example, if a drug is found to be effective 30 percent of the time it is used, we might assign a probability .3 that the drug is effective the next time it is used and .7 that it is not effective. This last example illustrates the intuitive frequency concept of probability. That is, if we have a probability p that an experiment will result in outcome A, then if we repeat this experiment a large number of times we should expect that the fraction of times that A will occur is about p. To check intuitive ideas like this, we shall find it helpful to look at some of these problems experimentally. We could, for example, toss a coin a large number of times and see if the fraction of times heads turns up is about 1/2. We could also simulate this experiment on a computer. Simulation We want to be able to perform an experiment that corresponds to a given set of probabilities; for example, m(ω1) = 1/2, m(ω2) = 1/3, and m(ω3) = 1/6. In this case, one could mark three faces of a six-sided die with an ω1, two faces with an ω2, and one face with an ω3. In the general case we assume that m(ω1), m(ω2), . . . , m(ωn) are all rational numbers, with least common denominator n. If n > 2, we can imagine a long cylindrical die with a cross-section that is a regular n-gon. If m(ωj) = nj/n, then we can label nj of the long faces of the cylinder with an ωj, and if one of the end faces comes up, we can just roll the die again. If n = 2, a coin could be used to perform the experiment. We will be particularly interested in repeating a chance experiment a large num- ber of times. Although the cylindrical die would be a convenient way to carry out a few repetitions, it would be difficult to carry out a large number of experiments. Since the modern computer can do a large number of operations in a very short time, it is natural to turn to the computer for this task. Random Numbers We must first find a computer analog of rolling a die. This is done on the computer by means of a random number generator. Depending upon the particular software package, the computer can be asked for a real number between 0 and 1, or an integer in a given set of consecutive integers. In the first case, the real numbers are chosen in such a way that the probability that the number lies in any particular subinterval of this unit interval is equal to the length of the subinterval. In the second case, each integer has the same probability of being chosen.
prob_Page_10_Chunk4849
1.1. SIMULATION OF DISCRETE PROBABILITIES 3 .203309 .762057 .151121 .623868 .932052 .415178 .716719 .967412 .069664 .670982 .352320 .049723 .750216 .784810 .089734 .966730 .946708 .380365 .027381 .900794 Table 1.1: Sample output of the program RandomNumbers. Let X be a random variable with distribution function m(ω), where ω is in the set {ω1, ω2, ω3}, and m(ω1) = 1/2, m(ω2) = 1/3, and m(ω3) = 1/6. If our computer package can return a random integer in the set {1, 2, ..., 6}, then we simply ask it to do so, and make 1, 2, and 3 correspond to ω1, 4 and 5 correspond to ω2, and 6 correspond to ω3. If our computer package returns a random real number r in the interval (0, 1), then the expression ⌊6r⌋+ 1 will be a random integer between 1 and 6. (The notation ⌊x⌋means the greatest integer not exceeding x, and is read “floor of x.”) The method by which random real numbers are generated on a computer is described in the historical discussion at the end of this section. The following example gives sample output of the program RandomNumbers. Example 1.1 (Random Number Generation) The program RandomNumbers generates n random real numbers in the interval [0, 1], where n is chosen by the user. When we ran the program with n = 20, we obtained the data shown in Table 1.1. 2 Example 1.2 (Coin Tossing) As we have noted, our intuition suggests that the probability of obtaining a head on a single toss of a coin is 1/2. To have the computer toss a coin, we can ask it to pick a random real number in the interval [0, 1] and test to see if this number is less than 1/2. If so, we shall call the outcome heads; if not we call it tails. Another way to proceed would be to ask the computer to pick a random integer from the set {0, 1}. The program CoinTosses carries out the experiment of tossing a coin n times. Running this program, with n = 20, resulted in: THTTTHTTTTHTTTTTHHTT. Note that in 20 tosses, we obtained 5 heads and 15 tails. Let us toss a coin n times, where n is much larger than 20, and see if we obtain a proportion of heads closer to our intuitive guess of 1/2. The program CoinTosses keeps track of the number of heads. When we ran this program with n = 1000, we obtained 494 heads. When we ran it with n = 10000, we obtained 5039 heads.
prob_Page_11_Chunk4850
4 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS We notice that when we tossed the coin 10,000 times, the proportion of heads was close to the “true value” .5 for obtaining a head when a coin is tossed. A math- ematical model for this experiment is called Bernoulli Trials (see Chapter 3). The Law of Large Numbers, which we shall study later (see Chapter 8), will show that in the Bernoulli Trials model, the proportion of heads should be near .5, consistent with our intuitive idea of the frequency interpretation of probability. Of course, our program could be easily modified to simulate coins for which the probability of a head is p, where p is a real number between 0 and 1. 2 In the case of coin tossing, we already knew the probability of the event occurring on each experiment. The real power of simulation comes from the ability to estimate probabilities when they are not known ahead of time. This method has been used in the recent discoveries of strategies that make the casino game of blackjack favorable to the player. We illustrate this idea in a simple situation in which we can compute the true probability and see how effective the simulation is. Example 1.3 (Dice Rolling) We consider a dice game that played an important role in the historical development of probability. The famous letters between Pas- cal and Fermat, which many believe started a serious study of probability, were instigated by a request for help from a French nobleman and gambler, Chevalier de M´er´e. It is said that de M´er´e had been betting that, in four rolls of a die, at least one six would turn up. He was winning consistently and, to get more people to play, he changed the game to bet that, in 24 rolls of two dice, a pair of sixes would turn up. It is claimed that de M´er´e lost with 24 and felt that 25 rolls were necessary to make the game favorable. It was un grand scandale that mathematics was wrong. We shall try to see if de M´er´e is correct by simulating his various bets. The program DeMere1 simulates a large number of experiments, seeing, in each one, if a six turns up in four rolls of a die. When we ran this program for 1000 plays, a six came up in the first four rolls 48.6 percent of the time. When we ran it for 10,000 plays this happened 51.98 percent of the time. We note that the result of the second run suggests that de M´er´e was correct in believing that his bet with one die was favorable; however, if we had based our conclusion on the first run, we would have decided that he was wrong. Accurate results by simulation require a large number of experiments. 2 The program DeMere2 simulates de M´er´e’s second bet that a pair of sixes will occur in n rolls of a pair of dice. The previous simulation shows that it is important to know how many trials we should simulate in order to expect a certain degree of accuracy in our approximation. We shall see later that in these types of experiments, a rough rule of thumb is that, at least 95% of the time, the error does not exceed the reciprocal of the square root of the number of trials. Fortunately, for this dice game, it will be easy to compute the exact probabilities. We shall show in the next section that for the first bet the probability that de M´er´e wins is 1 −(5/6)4 = .518.
prob_Page_12_Chunk4851
1.1. SIMULATION OF DISCRETE PROBABILITIES 5 5 10 15 20 25 30 35 40 -10 -8 -6 -4 -2 2 4 6 8 10 Figure 1.1: Peter’s winnings in 40 plays of heads or tails. One can understand this calculation as follows: The probability that no 6 turns up on the first toss is (5/6). The probability that no 6 turns up on either of the first two tosses is (5/6)2. Reasoning in the same way, the probability that no 6 turns up on any of the first four tosses is (5/6)4. Thus, the probability of at least one 6 in the first four tosses is 1 −(5/6)4. Similarly, for the second bet, with 24 rolls, the probability that de M´er´e wins is 1 −(35/36)24 = .491, and for 25 rolls it is 1 −(35/36)25 = .506. Using the rule of thumb mentioned above, it would require 27,000 rolls to have a reasonable chance to determine these probabilities with sufficient accuracy to assert that they lie on opposite sides of .5. It is interesting to ponder whether a gambler can detect such probabilities with the required accuracy from gambling experience. Some writers on the history of probability suggest that de M´er´e was, in fact, just interested in these problems as intriguing probability problems. Example 1.4 (Heads or Tails) For our next example, we consider a problem where the exact answer is difficult to obtain but for which simulation easily gives the qualitative results. Peter and Paul play a game called heads or tails. In this game, a fair coin is tossed a sequence of times—we choose 40. Each time a head comes up Peter wins 1 penny from Paul, and each time a tail comes up Peter loses 1 penny to Paul. For example, if the results of the 40 tosses are THTHHHHTTHTHHTTHHTTTTHHHTHHTHHHTHHHTTTHH. Peter’s winnings may be graphed as in Figure 1.1. Peter has won 6 pennies in this particular game. It is natural to ask for the probability that he will win j pennies; here j could be any even number from −40 to 40. It is reasonable to guess that the value of j with the highest probability is j = 0, since this occurs when the number of heads equals the number of tails. Similarly, we would guess that the values of j with the lowest probabilities are j = ±40.
prob_Page_13_Chunk4852
6 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS A second interesting question about this game is the following: How many times in the 40 tosses will Peter be in the lead? Looking at the graph of his winnings (Figure 1.1), we see that Peter is in the lead when his winnings are positive, but we have to make some convention when his winnings are 0 if we want all tosses to contribute to the number of times in the lead. We adopt the convention that, when Peter’s winnings are 0, he is in the lead if he was ahead at the previous toss and not if he was behind at the previous toss. With this convention, Peter is in the lead 34 times in our example. Again, our intuition might suggest that the most likely number of times to be in the lead is 1/2 of 40, or 20, and the least likely numbers are the extreme cases of 40 or 0. It is easy to settle this by simulating the game a large number of times and keeping track of the number of times that Peter’s final winnings are j, and the number of times that Peter ends up being in the lead by k. The proportions over all games then give estimates for the corresponding probabilities. The program HTSimulation carries out this simulation. Note that when there are an even number of tosses in the game, it is possible to be in the lead only an even number of times. We have simulated this game 10,000 times. The results are shown in Figures 1.2 and 1.3. These graphs, which we call spike graphs, were generated using the program Spikegraph. The vertical line, or spike, at position x on the horizontal axis, has a height equal to the proportion of outcomes which equal x. Our intuition about Peter’s final winnings was quite correct, but our intuition about the number of times Peter was in the lead was completely wrong. The simulation suggests that the least likely number of times in the lead is 20 and the most likely is 0 or 40. This is indeed correct, and the explanation for it is suggested by playing the game of heads or tails with a large number of tosses and looking at a graph of Peter’s winnings. In Figure 1.4 we show the results of a simulation of the game, for 1000 tosses and in Figure 1.5 for 10,000 tosses. In the second example Peter was ahead most of the time. It is a remarkable fact, however, that, if play is continued long enough, Peter’s winnings will continue to come back to 0, but there will be very long times between the times that this happens. These and related results will be discussed in Chapter 12. 2 In all of our examples so far, we have simulated equiprobable outcomes. We illustrate next an example where the outcomes are not equiprobable. Example 1.5 (Horse Races) Four horses (Acorn, Balky, Chestnut, and Dolby) have raced many times. It is estimated that Acorn wins 30 percent of the time, Balky 40 percent of the time, Chestnut 20 percent of the time, and Dolby 10 percent of the time. We can have our computer carry out one race as follows: Choose a random number x. If x < .3 then we say that Acorn won. If .3 ≤x < .7 then Balky wins. If .7 ≤x < .9 then Chestnut wins. Finally, if .9 ≤x then Dolby wins. The program HorseRace uses this method to simulate the outcomes of n races. Running this program for n = 10 we found that Acorn won 40 percent of the time, Balky 20 percent of the time, Chestnut 10 percent of the time, and Dolby 30 percent
prob_Page_14_Chunk4853
1.1. SIMULATION OF DISCRETE PROBABILITIES 7 Figure 1.2: Distribution of winnings. Figure 1.3: Distribution of number of times in the lead.
prob_Page_15_Chunk4854
8 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS 200 400 600 800 1000 1000 plays -50 -40 -30 -20 -10 0 10 20 Figure 1.4: Peter’s winnings in 1000 plays of heads or tails. 2000 4000 6000 8000 10000 10000 plays 0 50 100 150 200 Figure 1.5: Peter’s winnings in 10,000 plays of heads or tails.
prob_Page_16_Chunk4855
1.1. SIMULATION OF DISCRETE PROBABILITIES 9 of the time. A larger number of races would be necessary to have better agreement with the past experience. Therefore we ran the program to simulate 1000 races with our four horses. Although very tired after all these races, they performed in a manner quite consistent with our estimates of their abilities. Acorn won 29.8 percent of the time, Balky 39.4 percent, Chestnut 19.5 percent, and Dolby 11.3 percent of the time. The program GeneralSimulation uses this method to simulate repetitions of an arbitrary experiment with a finite number of outcomes occurring with known probabilities. 2 Historical Remarks Anyone who plays the same chance game over and over is really carrying out a sim- ulation, and in this sense the process of simulation has been going on for centuries. As we have remarked, many of the early problems of probability might well have been suggested by gamblers’ experiences. It is natural for anyone trying to understand probability theory to try simple experiments by tossing coins, rolling dice, and so forth. The naturalist Buffon tossed a coin 4040 times, resulting in 2048 heads and 1992 tails. He also estimated the number π by throwing needles on a ruled surface and recording how many times the needles crossed a line (see Section 2.1). The English biologist W. F. R. Weldon1 recorded 26,306 throws of 12 dice, and the Swiss scientist Rudolf Wolf2 recorded 100,000 throws of a single die without a computer. Such experiments are very time- consuming and may not accurately represent the chance phenomena being studied. For example, for the dice experiments of Weldon and Wolf, further analysis of the recorded data showed a suspected bias in the dice. The statistician Karl Pearson analyzed a large number of outcomes at certain roulette tables and suggested that the wheels were biased. He wrote in 1894: Clearly, since the Casino does not serve the valuable end of huge lab- oratory for the preparation of probability statistics, it has no scientific raison d’ˆetre. Men of science cannot have their most refined theories disregarded in this shameless manner! The French Government must be urged by the hierarchy of science to close the gaming-saloons; it would be, of course, a graceful act to hand over the remaining resources of the Casino to the Acad´emie des Sciences for the endowment of a laboratory of orthodox probability; in particular, of the new branch of that study, the application of the theory of chance to the biological problems of evolution, which is likely to occupy so much of men’s thoughts in the near future.3 However, these early experiments were suggestive and led to important discov- eries in probability and statistics. They led Pearson to the chi-squared test, which 1T. C. Fry, Probability and Its Engineering Uses, 2nd ed. (Princeton: Van Nostrand, 1965). 2E. Czuber, Wahrscheinlichkeitsrechnung, 3rd ed. (Berlin: Teubner, 1914). 3K. Pearson, “Science and Monte Carlo,” Fortnightly Review, vol. 55 (1894), p. 193; cited in S. M. Stigler, The History of Statistics (Cambridge: Harvard University Press, 1986).
prob_Page_17_Chunk4856
10 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS is of great importance in testing whether observed data fit a given probability dis- tribution. By the early 1900s it was clear that a better way to generate random numbers was needed. In 1927, L. H. C. Tippett published a list of 41,600 digits obtained by selecting numbers haphazardly from census reports. In 1955, RAND Corporation printed a table of 1,000,000 random numbers generated from electronic noise. The advent of the high-speed computer raised the possibility of generating random num- bers directly on the computer, and in the late 1940s John von Neumann suggested that this be done as follows: Suppose that you want a random sequence of four-digit numbers. Choose any four-digit number, say 6235, to start. Square this number to obtain 38,875,225. For the second number choose the middle four digits of this square (i.e., 8752). Do the same process starting with 8752 to get the third number, and so forth. More modern methods involve the concept of modular arithmetic. If a is an integer and m is a positive integer, then by a (mod m) we mean the remainder when a is divided by m. For example, 10 (mod 4) = 2, 8 (mod 2) = 0, and so forth. To generate a random sequence X0, X1, X2, . . . of numbers choose a starting number X0 and then obtain the numbers Xn+1 from Xn by the formula Xn+1 = (aXn + c) (mod m) , where a, c, and m are carefully chosen constants. The sequence X0, X1, X2, . . . is then a sequence of integers between 0 and m −1. To obtain a sequence of real numbers in [0, 1), we divide each Xj by m. The resulting sequence consists of rational numbers of the form j/m, where 0 ≤j ≤m −1. Since m is usually a very large integer, we think of the numbers in the sequence as being random real numbers in [0, 1). For both von Neumann’s squaring method and the modular arithmetic technique the sequence of numbers is actually completely determined by the first number. Thus, there is nothing really random about these sequences. However, they produce numbers that behave very much as theory would predict for random experiments. To obtain different sequences for different experiments the initial number X0 is chosen by some other procedure that might involve, for example, the time of day.4 During the Second World War, physicists at the Los Alamos Scientific Labo- ratory needed to know, for purposes of shielding, how far neutrons travel through various materials. This question was beyond the reach of theoretical calculations. Daniel McCracken, writing in the Scientific American, states: The physicists had most of the necessary data: they knew the average distance a neutron of a given speed would travel in a given substance before it collided with an atomic nucleus, what the probabilities were that the neutron would bounce offinstead of being absorbed by the nucleus, how much energy the neutron was likely to lose after a given 4For a detailed discussion of random numbers, see D. E. Knuth, The Art of Computer Pro- gramming, vol. II (Reading: Addison-Wesley, 1969).
prob_Page_18_Chunk4857
1.1. SIMULATION OF DISCRETE PROBABILITIES 11 collision and so on.5 John von Neumann and Stanislas Ulam suggested that the problem be solved by modeling the experiment by chance devices on a computer. Their work being secret, it was necessary to give it a code name. Von Neumann chose the name “Monte Carlo.” Since that time, this method of simulation has been called the Monte Carlo Method. William Feller indicated the possibilities of using computer simulations to illus- trate basic concepts in probability in his book An Introduction to Probability Theory and Its Applications. In discussing the problem about the number of times in the lead in the game of “heads or tails” Feller writes: The results concerning fluctuations in coin tossing show that widely held beliefs about the law of large numbers are fallacious. These results are so amazing and so at variance with common intuition that even sophisticated colleagues doubted that coins actually misbehave as theory predicts. The record of a simulated experiment is therefore included.6 Feller provides a plot showing the result of 10,000 plays of heads or tails similar to that in Figure 1.5. The martingale betting system described in Exercise 10 has a long and interest- ing history. Russell Barnhart pointed out to the authors that its use can be traced back at least to 1754, when Casanova, writing in his memoirs, History of My Life, writes She [Casanova’s mistress] made me promise to go to the casino [the Ridotto in Venice] for money to play in partnership with her. I went there and took all the gold I found, and, determinedly doubling my stakes according to the system known as the martingale, I won three or four times a day during the rest of the Carnival. I never lost the sixth card. If I had lost it, I should have been out of funds, which amounted to two thousand zecchini.7 Even if there were no zeros on the roulette wheel so the game was perfectly fair, the martingale system, or any other system for that matter, cannot make the game into a favorable game. The idea that a fair game remains fair and unfair games remain unfair under gambling systems has been exploited by mathematicians to obtain important results in the study of probability. We will introduce the general concept of a martingale in Chapter 6. The word martingale itself also has an interesting history. The origin of the word is obscure. A recent version of the Oxford English Dictionary gives examples 5D. D. McCracken, “The Monte Carlo Method,” Scientific American, vol. 192 (May 1955), p. 90. 6W. Feller, Introduction to Probability Theory and its Applications, vol. 1, 3rd ed. (New York: John Wiley & Sons, 1968), p. xi. 7G. Casanova, History of My Life, vol. IV, Chap. 7, trans. W. R. Trask (New York: Harcourt- Brace, 1968), p. 124.
prob_Page_19_Chunk4858
12 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS of its use in the early 1600s and says that its probable origin is the reference in Rabelais’s Book One, Chapter 20: Everything was done as planned, the only thing being that Gargantua doubted if they would be able to find, right away, breeches suitable to the old fellow’s legs; he was doubtful, also, as to what cut would be most becoming to the orator—the martingale, which has a draw-bridge effect in the seat, to permit doing one’s business more easily; the sailor-style, which affords more comfort for the kidneys; the Swiss, which is warmer on the belly; or the codfish-tail, which is cooler on the loins.8 Dominic Lusinchi noted an earlier occurrence of the word martingale. Accord- ing to the French dictionary Le Petit Robert, the word comes from the Proven¸cal word “martegalo,” which means “from Martigues.” Martigues is a town due west of Merseille. The dictionary gives the example of “chausses `a la martinguale” (which means Martigues-style breeches) and the date 1491. In modern uses martingale has several different meanings, all related to holding down, in addition to the gambling use. For example, it is a strap on a horse’s harness used to hold down the horse’s head, and also part of a sailing rig used to hold down the bowsprit. The Labouchere system described in Exercise 9 is named after Henry du Pre Labouchere (1831–1912), an English journalist and member of Parliament. Labou- chere attributed the system to Condorcet. Condorcet (1743–1794) was a political leader during the time of the French revolution who was interested in applying prob- ability theory to economics and politics. For example, he calculated the probability that a jury using majority vote will give a correct decision if each juror has the same probability of deciding correctly. His writings provided a wealth of ideas on how probability might be applied to human affairs.9 Exercises 1 Modify the program CoinTosses to toss a coin n times and print out after every 100 tosses the proportion of heads minus 1/2. Do these numbers appear to approach 0 as n increases? Modify the program again to print out, every 100 times, both of the following quantities: the proportion of heads minus 1/2, and the number of heads minus half the number of tosses. Do these numbers appear to approach 0 as n increases? 2 Modify the program CoinTosses so that it tosses a coin n times and records whether or not the proportion of heads is within .1 of .5 (i.e., between .4 and .6). Have your program repeat this experiment 100 times. About how large must n be so that approximately 95 out of 100 times the proportion of heads is between .4 and .6? 8Quoted in the Portable Rabelais, ed. S. Putnam (New York: Viking, 1946), p. 113. 9Le Marquise de Condorcet, Essai sur l’Application de l’Analyse `a la Probabilit´e d`es D´ecisions Rendues a la Pluralit´e des Voix (Paris: Imprimerie Royale, 1785).
prob_Page_20_Chunk4859
1.1. SIMULATION OF DISCRETE PROBABILITIES 13 3 In the early 1600s, Galileo was asked to explain the fact that, although the number of triples of integers from 1 to 6 with sum 9 is the same as the number of such triples with sum 10, when three dice are rolled, a 9 seemed to come up less often than a 10—supposedly in the experience of gamblers. (a) Write a program to simulate the roll of three dice a large number of times and keep track of the proportion of times that the sum is 9 and the proportion of times it is 10. (b) Can you conclude from your simulations that the gamblers were correct? 4 In raquetball, a player continues to serve as long as she is winning; a point is scored only when a player is serving and wins the volley. The first player to win 21 points wins the game. Assume that you serve first and have a probability .6 of winning a volley when you serve and probability .5 when your opponent serves. Estimate, by simulation, the probability that you will win a game. 5 Consider the bet that all three dice will turn up sixes at least once in n rolls of three dice. Calculate f(n), the probability of at least one triple-six when three dice are rolled n times. Determine the smallest value of n necessary for a favorable bet that a triple-six will occur when three dice are rolled n times. (DeMoivre would say it should be about 216 log2 = 149.7 and so would answer 150—see Exercise 1.2.17. Do you agree with him?) 6 In Las Vegas, a roulette wheel has 38 slots numbered 0, 00, 1, 2, . . . , 36. The 0 and 00 slots are green and half of the remaining 36 slots are red and half are black. A croupier spins the wheel and throws in an ivory ball. If you bet 1 dollar on red, you win 1 dollar if the ball stops in a red slot and otherwise you lose 1 dollar. Write a program to find the total winnings for a player who makes 1000 bets on red. 7 Another form of bet for roulette is to bet that a specific number (say 17) will turn up. If the ball stops on your number, you get your dollar back plus 35 dollars. If not, you lose your dollar. Write a program that will plot your winnings when you make 500 plays of roulette at Las Vegas, first when you bet each time on red (see Exercise 6), and then for a second visit to Las Vegas when you make 500 plays betting each time on the number 17. What differences do you see in the graphs of your winnings on these two occasions? 8 An astute student noticed that, in our simulation of the game of heads or tails (see Example 1.4), the proportion of times the player is always in the lead is very close to the proportion of times that the player’s total winnings end up 0. Work out these probabilities by enumeration of all cases for two tosses and for four tosses, and see if you think that these probabilities are, in fact, the same. 9 The Labouchere system for roulette is played as follows. Write down a list of numbers, usually 1, 2, 3, 4. Bet the sum of the first and last, 1 + 4 = 5, on
prob_Page_21_Chunk4860
14 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS red. If you win, delete the first and last numbers from your list. If you lose, add the amount that you last bet to the end of your list. Then use the new list and bet the sum of the first and last numbers (if there is only one number, bet that amount). Continue until your list becomes empty. Show that, if this happens, you win the sum, 1 + 2 + 3 + 4 = 10, of your original list. Simulate this system and see if you do always stop and, hence, always win. If so, why is this not a foolproof gambling system? 10 Another well-known gambling system is the martingale doubling system. Sup- pose that you are betting on red to turn up in roulette. Every time you win, bet 1 dollar next time. Every time you lose, double your previous bet. Suppose that you use this system until you have won at least 5 dollars or you have lost more than 100 dollars. Write a program to simulate this and play it a number of times and see how you do. In his book The Newcomes, W. M. Thack- eray remarks “You have not played as yet? Do not do so; above all avoid a martingale if you do.”10 Was this good advice? 11 Modify the program HTSimulation so that it keeps track of the maximum of Peter’s winnings in each game of 40 tosses. Have your program print out the proportion of times that your total winnings take on values 0, 2, 4, . . . , 40. Calculate the corresponding exact probabilities for games of two tosses and four tosses. 12 In an upcoming national election for the President of the United States, a pollster plans to predict the winner of the popular vote by taking a random sample of 1000 voters and declaring that the winner will be the one obtaining the most votes in his sample. Suppose that 48 percent of the voters plan to vote for the Republican candidate and 52 percent plan to vote for the Democratic candidate. To get some idea of how reasonable the pollster’s plan is, write a program to make this prediction by simulation. Repeat the simulation 100 times and see how many times the pollster’s prediction would come true. Repeat your experiment, assuming now that 49 percent of the population plan to vote for the Republican candidate; first with a sample of 1000 and then with a sample of 3000. (The Gallup Poll uses about 3000.) (This idea is discussed further in Chapter 9, Section 9.1.) 13 The psychologist Tversky and his colleagues11 say that about four out of five people will answer (a) to the following question: A certain town is served by two hospitals. In the larger hospital about 45 babies are born each day, and in the smaller hospital 15 babies are born each day. Although the overall proportion of boys is about 50 percent, the actual proportion at either hospital may be more or less than 50 percent on any day. 10W. M. Thackerey, The Newcomes (London: Bradbury and Evans, 1854–55). 11See K. McKean, “Decisions, Decisions,” Discover, June 1985, pp. 22–31. Kevin McKean, Discover Magazine, c⃝1987 Family Media, Inc. Reprinted with permission. This popular article reports on the work of Tverksy et. al. in Judgement Under Uncertainty: Heuristics and Biases (Cambridge: Cambridge University Press, 1982).
prob_Page_22_Chunk4861
1.1. SIMULATION OF DISCRETE PROBABILITIES 15 At the end of a year, which hospital will have the greater number of days on which more than 60 percent of the babies born were boys? (a) the large hospital (b) the small hospital (c) neither—the number of days will be about the same. Assume that the probability that a baby is a boy is .5 (actual estimates make this more like .513). Decide, by simulation, what the right answer is to the question. Can you suggest why so many people go wrong? 14 You are offered the following game. A fair coin will be tossed until the first time it comes up heads. If this occurs on the jth toss you are paid 2j dollars. You are sure to win at least 2 dollars so you should be willing to pay to play this game—but how much? Few people would pay as much as 10 dollars to play this game. See if you can decide, by simulation, a reasonable amount that you would be willing to pay, per game, if you will be allowed to make a large number of plays of the game. Does the amount that you would be willing to pay per game depend upon the number of plays that you will be allowed? 15 Tversky and his colleagues12 studied the records of 48 of the Philadelphia 76ers basketball games in the 1980–81 season to see if a player had times when he was hot and every shot went in, and other times when he was cold and barely able to hit the backboard. The players estimated that they were about 25 percent more likely to make a shot after a hit than after a miss. In fact, the opposite was true—the 76ers were 6 percent more likely to score after a miss than after a hit. Tversky reports that the number of hot and cold streaks was about what one would expect by purely random effects. Assuming that a player has a fifty-fifty chance of making a shot and makes 20 shots a game, estimate by simulation the proportion of the games in which the player will have a streak of 5 or more hits. 16 Estimate, by simulation, the average number of children there would be in a family if all people had children until they had a boy. Do the same if all people had children until they had at least one boy and at least one girl. How many more children would you expect to find under the second scheme than under the first in 100,000 families? (Assume that boys and girls are equally likely.) 17 Mathematicians have been known to get some of the best ideas while sitting in a cafe, riding on a bus, or strolling in the park. In the early 1900s the famous mathematician George P´olya lived in a hotel near the woods in Zurich. He liked to walk in the woods and think about mathematics. P´olya describes the following incident: 12ibid.
prob_Page_23_Chunk4862
16 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS 0 1 2 3 -1 -2 -3 c. Random walk in three dimensions. b. Random walk in two dimensions. a. Random walk in one dimension. Figure 1.6: Random walk.
prob_Page_24_Chunk4863
1.1. SIMULATION OF DISCRETE PROBABILITIES 17 At the hotel there lived also some students with whom I usually took my meals and had friendly relations. On a certain day one of them expected the visit of his fianc´ee, what (sic) I knew, but I did not foresee that he and his fianc´ee would also set out for a stroll in the woods, and then suddenly I met them there. And then I met them the same morning repeatedly, I don’t remember how many times, but certainly much too often and I felt embarrassed: It looked as if I was snooping around which was, I assure you, not the case.13 This set him to thinking about whether random walkers were destined to meet. P´olya considered random walkers in one, two, and three dimensions. In one dimension, he envisioned the walker on a very long street. At each intersec- tion the walker flips a fair coin to decide which direction to walk next (see Figure 1.6a). In two dimensions, the walker is walking on a grid of streets, and at each intersection he chooses one of the four possible directions with equal probability (see Figure 1.6b). In three dimensions (we might better speak of a random climber), the walker moves on a three-dimensional grid, and at each intersection there are now six different directions that the walker may choose, each with equal probability (see Figure 1.6c). The reader is referred to Section 12.1, where this and related problems are discussed. (a) Write a program to simulate a random walk in one dimension starting at 0. Have your program print out the lengths of the times between returns to the starting point (returns to 0). See if you can guess from this simulation the answer to the following question: Will the walker always return to his starting point eventually or might he drift away forever? (b) The paths of two walkers in two dimensions who meet after n steps can be considered to be a single path that starts at (0, 0) and returns to (0, 0) after 2n steps. This means that the probability that two random walkers in two dimensions meet is the same as the probability that a single walker in two dimensions ever returns to the starting point. Thus the question of whether two walkers are sure to meet is the same as the question of whether a single walker is sure to return to the starting point. Write a program to simulate a random walk in two dimensions and see if you think that the walker is sure to return to (0, 0). If so, P´olya would be sure to keep meeting his friends in the park. Perhaps by now you have conjectured the answer to the question: Is a random walker in one or two dimensions sure to return to the starting point? P´olya answered 13G. P´olya, “Two Incidents,” Scientists at Work: Festschrift in Honour of Herman Wold, ed. T. Dalenius, G. Karlsson, and S. Malmquist (Uppsala: Almquist & Wiksells Boktryckeri AB, 1970).
prob_Page_25_Chunk4864
18 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS this question for dimensions one, two, and three. He established the remarkable result that the answer is yes in one and two dimensions and no in three dimensions. (c) Write a program to simulate a random walk in three dimensions and see whether, from this simulation and the results of (a) and (b), you could have guessed P´olya’s result. 1.2 Discrete Probability Distributions In this book we shall study many different experiments from a probabilistic point of view. What is involved in this study will become evident as the theory is developed and examples are analyzed. However, the overall idea can be described and illus- trated as follows: to each experiment that we consider there will be associated a random variable, which represents the outcome of any particular experiment. The set of possible outcomes is called the sample space. In the first part of this section, we will consider the case where the experiment has only finitely many possible out- comes, i.e., the sample space is finite. We will then generalize to the case that the sample space is either finite or countably infinite. This leads us to the following definition. Random Variables and Sample Spaces Definition 1.1 Suppose we have an experiment whose outcome depends on chance. We represent the outcome of the experiment by a capital Roman letter, such as X, called a random variable. The sample space of the experiment is the set of all possible outcomes. If the sample space is either finite or countably infinite, the random variable is said to be discrete. 2 We generally denote a sample space by the capital Greek letter Ω. As stated above, in the correspondence between an experiment and the mathematical theory by which it is studied, the sample space Ωcorresponds to the set of possible outcomes of the experiment. We now make two additional definitions. These are subsidiary to the definition of sample space and serve to make precise some of the common terminology used in conjunction with sample spaces. First of all, we define the elements of a sample space to be outcomes. Second, each subset of a sample space is defined to be an event. Normally, we shall denote outcomes by lower case letters and events by capital letters. Example 1.6 A die is rolled once. We let X denote the outcome of this experiment. Then the sample space for this experiment is the 6-element set Ω= {1, 2, 3, 4, 5, 6} ,
prob_Page_26_Chunk4865
1.2. DISCRETE PROBABILITY DISTRIBUTIONS 19 where each outcome i, for i = 1, . . . , 6, corresponds to the number of dots on the face which turns up. The event E = {2, 4, 6} corresponds to the statement that the result of the roll is an even number. The event E can also be described by saying that X is even. Unless there is reason to believe the die is loaded, the natural assumption is that every outcome is equally likely. Adopting this convention means that we assign a probability of 1/6 to each of the six outcomes, i.e., m(i) = 1/6, for 1 ≤i ≤6. 2 Distribution Functions We next describe the assignment of probabilities. The definitions are motivated by the example above, in which we assigned to each outcome of the sample space a nonnegative number such that the sum of the numbers assigned is equal to 1. Definition 1.2 Let X be a random variable which denotes the value of the out- come of a certain experiment, and assume that this experiment has only finitely many possible outcomes. Let Ωbe the sample space of the experiment (i.e., the set of all possible values of X, or equivalently, the set of all possible outcomes of the experiment.) A distribution function for X is a real-valued function m whose domain is Ωand which satisfies: 1. m(ω) ≥0 , for all ω ∈Ω, and 2. P ω∈Ω m(ω) = 1 . For any subset E of Ω, we define the probability of E to be the number P(E) given by P(E) = X ω∈E m(ω) . 2 Example 1.7 Consider an experiment in which a coin is tossed twice. Let X be the random variable which corresponds to this experiment. We note that there are several ways to record the outcomes of this experiment. We could, for example, record the two tosses, in the order in which they occurred. In this case, we have Ω={HH,HT,TH,TT}. We could also record the outcomes by simply noting the number of heads that appeared. In this case, we have Ω={0,1,2}. Finally, we could record the two outcomes, without regard to the order in which they occurred. In this case, we have Ω={HH,HT,TT}. We will use, for the moment, the first of the sample spaces given above. We will assume that all four outcomes are equally likely, and define the distribution function m(ω) by m(HH) = m(HT) = m(TH) = m(TT) = 1 4 .
prob_Page_27_Chunk4866
20 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS Let E ={HH,HT,TH} be the event that at least one head comes up. Then, the probability of E can be calculated as follows: P(E) = m(HH) + m(HT) + m(TH) = 1 4 + 1 4 + 1 4 = 3 4 . Similarly, if F ={HH,HT} is the event that heads comes up on the first toss, then we have P(F) = m(HH) + m(HT) = 1 4 + 1 4 = 1 2 . 2 Example 1.8 (Example 1.6 continued) The sample space for the experiment in which the die is rolled is the 6-element set Ω= {1, 2, 3, 4, 5, 6}. We assumed that the die was fair, and we chose the distribution function defined by m(i) = 1 6, for i = 1, . . . , 6 . If E is the event that the result of the roll is an even number, then E = {2, 4, 6} and P(E) = m(2) + m(4) + m(6) = 1 6 + 1 6 + 1 6 = 1 2 . 2 Notice that it is an immediate consequence of the above definitions that, for every ω ∈Ω, P({ω}) = m(ω) . That is, the probability of the elementary event {ω}, consisting of a single outcome ω, is equal to the value m(ω) assigned to the outcome ω by the distribution function. Example 1.9 Three people, A, B, and C, are running for the same office, and we assume that one and only one of them wins. The sample space may be taken as the 3-element set Ω={A,B,C} where each element corresponds to the outcome of that candidate’s winning. Suppose that A and B have the same chance of winning, but that C has only 1/2 the chance of A or B. Then we assign m(A) = m(B) = 2m(C) . Since m(A) + m(B) + m(C) = 1 ,
prob_Page_28_Chunk4867
1.2. DISCRETE PROBABILITY DISTRIBUTIONS 21 we see that 2m(C) + 2m(C) + m(C) = 1 , which implies that 5m(C) = 1. Hence, m(A) = 2 5 , m(B) = 2 5 , m(C) = 1 5 . Let E be the event that either A or C wins. Then E ={A,C}, and P(E) = m(A) + m(C) = 2 5 + 1 5 = 3 5 . 2 In many cases, events can be described in terms of other events through the use of the standard constructions of set theory. We will briefly review the definitions of these constructions. The reader is referred to Figure 1.7 for Venn diagrams which illustrate these constructions. Let A and B be two sets. Then the union of A and B is the set A ∪B = {x | x ∈A or x ∈B} . The intersection of A and B is the set A ∩B = {x | x ∈A and x ∈B} . The difference of A and B is the set A −B = {x | x ∈A and x ̸∈B} . The set A is a subset of B, written A ⊂B, if every element of A is also an element of B. Finally, the complement of A is the set ˜A = {x | x ∈Ωand x ̸∈A} . The reason that these constructions are important is that it is typically the case that complicated events described in English can be broken down into simpler events using these constructions. For example, if A is the event that “it will snow tomorrow and it will rain the next day,” B is the event that “it will snow tomorrow,” and C is the event that “it will rain two days from now,” then A is the intersection of the events B and C. Similarly, if D is the event that “it will snow tomorrow or it will rain the next day,” then D = B ∪C. (Note that care must be taken here, because sometimes the word “or” in English means that exactly one of the two alternatives will occur. The meaning is usually clear from context. In this book, we will always use the word “or” in the inclusive sense, i.e., A or B means that at least one of the two events A, B is true.) The event ˜B is the event that “it will not snow tomorrow.” Finally, if E is the event that “it will snow tomorrow but it will not rain the next day,” then E = B −C.
prob_Page_29_Chunk4868
22 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS A B A B A B A A A B ∼ ⊃ ⊃ A B A B Figure 1.7: Basic set operations. Properties Theorem 1.1 The probabilities assigned to events by a distribution function on a sample space Ωsatisfy the following properties: 1. P(E) ≥0 for every E ⊂Ω. 2. P(Ω) = 1 . 3. If E ⊂F ⊂Ω, then P(E) ≤P(F) . 4. If A and B are disjoint subsets of Ω, then P(A ∪B) = P(A) + P(B) . 5. P( ˜A) = 1 −P(A) for every A ⊂Ω. Proof. For any event E the probability P(E) is determined from the distribution m by P(E) = X ω∈E m(ω) , for every E ⊂Ω. Since the function m is nonnegative, it follows that P(E) is also nonnegative. Thus, Property 1 is true. Property 2 is proved by the equations P(Ω) = X ω∈Ω m(ω) = 1 . Suppose that E ⊂F ⊂Ω. Then every element ω that belongs to E also belongs to F. Therefore, X ω∈E m(ω) ≤ X ω∈F m(ω) , since each term in the left-hand sum is in the right-hand sum, and all the terms in both sums are non-negative. This implies that P(E) ≤P(F) , and Property 3 is proved.
prob_Page_30_Chunk4869
1.2. DISCRETE PROBABILITY DISTRIBUTIONS 23 Suppose next that A and B are disjoint subsets of Ω. Then every element ω of A ∪B lies either in A and not in B or in B and not in A. It follows that P(A ∪B) = P ω∈A∪B m(ω) = P ω∈A m(ω) + P ω∈B m(ω) = P(A) + P(B) , and Property 4 is proved. Finally, to prove Property 5, consider the disjoint union Ω= A ∪˜A . Since P(Ω) = 1, the property of disjoint additivity (Property 4) implies that 1 = P(A) + P( ˜A) , whence P( ˜A) = 1 −P(A). 2 It is important to realize that Property 4 in Theorem 1.1 can be extended to more than two sets. The general finite additivity property is given by the following theorem. Theorem 1.2 If A1, . . . , An are pairwise disjoint subsets of Ω(i.e., no two of the Ai’s have an element in common), then P(A1 ∪· · · ∪An) = n X i=1 P(Ai) . Proof. Let ω be any element in the union A1 ∪· · · ∪An . Then m(ω) occurs exactly once on each side of the equality in the statement of the theorem. 2 We shall often use the following consequence of the above theorem. Theorem 1.3 Let A1, . . . , An be pairwise disjoint events with Ω= A1 ∪· · · ∪An, and let E be any event. Then P(E) = n X i=1 P(E ∩Ai) . Proof. The sets E ∩A1, . . . , E ∩An are pairwise disjoint, and their union is the set E. The result now follows from Theorem 1.2. 2
prob_Page_31_Chunk4870
24 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS Corollary 1.1 For any two events A and B, P(A) = P(A ∩B) + P(A ∩˜B) . 2 Property 4 can be generalized in another way. Suppose that A and B are subsets of Ωwhich are not necessarily disjoint. Then: Theorem 1.4 If A and B are subsets of Ω, then P(A ∪B) = P(A) + P(B) −P(A ∩B) . (1.1) Proof. The left side of Equation 1.1 is the sum of m(ω) for ω in either A or B. We must show that the right side of Equation 1.1 also adds m(ω) for ω in A or B. If ω is in exactly one of the two sets, then it is counted in only one of the three terms on the right side of Equation 1.1. If it is in both A and B, it is added twice from the calculations of P(A) and P(B) and subtracted once for P(A ∩B). Thus it is counted exactly once by the right side. Of course, if A ∩B = ∅, then Equation 1.1 reduces to Property 4. (Equation 1.1 can also be generalized; see Theorem 3.8.) 2 Tree Diagrams Example 1.10 Let us illustrate the properties of probabilities of events in terms of three tosses of a coin. When we have an experiment which takes place in stages such as this, we often find it convenient to represent the outcomes by a tree diagram as shown in Figure 1.8. A path through the tree corresponds to a possible outcome of the experiment. For the case of three tosses of a coin, we have eight paths ω1, ω2, . . . , ω8 and, assuming each outcome to be equally likely, we assign equal weight, 1/8, to each path. Let E be the event “at least one head turns up.” Then ˜E is the event “no heads turn up.” This event occurs for only one outcome, namely, ω8 = TTT. Thus, ˜E = {TTT} and we have P( ˜E) = P({TTT}) = m(TTT) = 1 8 . By Property 5 of Theorem 1.1, P(E) = 1 −P( ˜E) = 1 −1 8 = 7 8 . Note that we shall often find it is easier to compute the probability that an event does not happen rather than the probability that it does. We then use Property 5 to obtain the desired probability.
prob_Page_32_Chunk4871
1.2. DISCRETE PROBABILITY DISTRIBUTIONS 25 First toss Second toss Third toss Outcome H H H H H H T T T T T T (Start) ω ω ω ω ω ω ω ω 1 2 3 4 5 6 7 8 H T Figure 1.8: Tree diagram for three tosses of a coin. Let A be the event “the first outcome is a head,” and B the event “the second outcome is a tail.” By looking at the paths in Figure 1.8, we see that P(A) = P(B) = 1 2 . Moreover, A∩B = {ω3, ω4}, and so P(A∩B) = 1/4. Using Theorem 1.4, we obtain P(A ∪B) = P(A) + P(B) −P(A ∩B) = 1 2 + 1 2 −1 4 = 3 4 . Since A ∪B is the 6-element set, A ∪B = {HHH,HHT,HTH,HTT,TTH,TTT} , we see that we obtain the same result by direct enumeration. 2 In our coin tossing examples and in the die rolling example, we have assigned an equal probability to each possible outcome of the experiment. Corresponding to this method of assigning probabilities, we have the following definitions. Uniform Distribution Definition 1.3 The uniform distribution on a sample space Ωcontaining n ele- ments is the function m defined by m(ω) = 1 n , for every ω ∈Ω. 2
prob_Page_33_Chunk4872
26 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS It is important to realize that when an experiment is analyzed to describe its possible outcomes, there is no single correct choice of sample space. For the ex- periment of tossing a coin twice in Example 1.2, we selected the 4-element set Ω={HH,HT,TH,TT} as a sample space and assigned the uniform distribution func- tion. These choices are certainly intuitively natural. On the other hand, for some purposes it may be more useful to consider the 3-element sample space ¯Ω= {0, 1, 2} in which 0 is the outcome “no heads turn up,” 1 is the outcome “exactly one head turns up,” and 2 is the outcome “two heads turn up.” The distribution function ¯m on ¯Ωdefined by the equations ¯m(0) = 1 4 , ¯m(1) = 1 2 , ¯m(2) = 1 4 is the one corresponding to the uniform probability density on the original sample space Ω. Notice that it is perfectly possible to choose a different distribution func- tion. For example, we may consider the uniform distribution function on ¯Ω, which is the function ¯q defined by ¯q(0) = ¯q(1) = ¯q(2) = 1 3 . Although ¯q is a perfectly good distribution function, it is not consistent with ob- served data on coin tossing. Example 1.11 Consider the experiment that consists of rolling a pair of dice. We take as the sample space Ωthe set of all ordered pairs (i, j) of integers with 1 ≤i ≤6 and 1 ≤j ≤6. Thus, Ω= { (i, j) : 1 ≤i, j ≤6 } . (There is at least one other “reasonable” choice for a sample space, namely the set of all unordered pairs of integers, each between 1 and 6. For a discussion of why we do not use this set, see Example 3.14.) To determine the size of Ω, we note that there are six choices for i, and for each choice of i there are six choices for j, leading to 36 different outcomes. Let us assume that the dice are not loaded. In mathematical terms, this means that we assume that each of the 36 outcomes is equally likely, or equivalently, that we adopt the uniform distribution function on Ωby setting m((i, j)) = 1 36, 1 ≤i, j ≤6 . What is the probability of getting a sum of 7 on the roll of two dice—or getting a sum of 11? The first event, denoted by E, is the subset E = {(1, 6), (6, 1), (2, 5), (5, 2), (3, 4), (4, 3)} . A sum of 11 is the subset F given by F = {(5, 6), (6, 5)} . Consequently, P(E) = P ω∈E m(ω) = 6 · 1 36 = 1 6 , P(F) = P ω∈F m(ω) = 2 · 1 36 = 1 18 .
prob_Page_34_Chunk4873
1.2. DISCRETE PROBABILITY DISTRIBUTIONS 27 What is the probability of getting neither snakeeyes (double ones) nor boxcars (double sixes)? The event of getting either one of these two outcomes is the set E = {(1, 1), (6, 6)} . Hence, the probability of obtaining neither is given by P( ˜E) = 1 −P(E) = 1 −2 36 = 17 18 . 2 In the above coin tossing and the dice rolling experiments, we have assigned an equal probability to each outcome. That is, in each example, we have chosen the uniform distribution function. These are the natural choices provided the coin is a fair one and the dice are not loaded. However, the decision as to which distribution function to select to describe an experiment is not a part of the basic mathemat- ical theory of probability. The latter begins only when the sample space and the distribution function have already been defined. Determination of Probabilities It is important to consider ways in which probability distributions are determined in practice. One way is by symmetry. For the case of the toss of a coin, we do not see any physical difference between the two sides of a coin that should affect the chance of one side or the other turning up. Similarly, with an ordinary die there is no essential difference between any two sides of the die, and so by symmetry we assign the same probability for any possible outcome. In general, considerations of symmetry often suggest the uniform distribution function. Care must be used here. We should not always assume that, just because we do not know any reason to suggest that one outcome is more likely than another, it is appropriate to assign equal probabilities. For example, consider the experiment of guessing the sex of a newborn child. It has been observed that the proportion of newborn children who are boys is about .513. Thus, it is more appropriate to assign a distribution function which assigns probability .513 to the outcome boy and probability .487 to the outcome girl than to assign probability 1/2 to each outcome. This is an example where we use statistical observations to determine probabilities. Note that these probabilities may change with new studies and may vary from country to country. Genetic engineering might even allow an individual to influence this probability for a particular case. Odds Statistical estimates for probabilities are fine if the experiment under consideration can be repeated a number of times under similar circumstances. However, assume that, at the beginning of a football season, you want to assign a probability to the event that Dartmouth will beat Harvard. You really do not have data that relates to this year’s football team. However, you can determine your own personal probability
prob_Page_35_Chunk4874
28 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS by seeing what kind of a bet you would be willing to make. For example, suppose that you are willing to make a 1 dollar bet giving 2 to 1 odds that Dartmouth will win. Then you are willing to pay 2 dollars if Dartmouth loses in return for receiving 1 dollar if Dartmouth wins. This means that you think the appropriate probability for Dartmouth winning is 2/3. Let us look more carefully at the relation between odds and probabilities. Sup- pose that we make a bet at r to 1 odds that an event E occurs. This means that we think that it is r times as likely that E will occur as that E will not occur. In general, r to s odds will be taken to mean the same thing as r/s to 1, i.e., the ratio between the two numbers is the only quantity of importance when stating odds. Now if it is r times as likely that E will occur as that E will not occur, then the probability that E occurs must be r/(r + 1), since we have P(E) = r P( ˜E) and P(E) + P( ˜E) = 1 . In general, the statement that the odds are r to s in favor of an event E occurring is equivalent to the statement that P(E) = r/s (r/s) + 1 = r r + s . If we let P(E) = p, then the above equation can easily be solved for r/s in terms of p; we obtain r/s = p/(1 −p). We summarize the above discussion in the following definition. Definition 1.4 If P(E) = p, the odds in favor of the event E occurring are r : s (r to s) where r/s = p/(1 −p). If r and s are given, then p can be found by using the equation p = r/(r + s). 2 Example 1.12 (Example 1.9 continued) In Example 1.9 we assigned probability 1/5 to the event that candidate C wins the race. Thus the odds in favor of C winning are 1/5 : 4/5. These odds could equally well have been written as 1 : 4, 2 : 8, and so forth. A bet that C wins is fair if we receive 4 dollars if C wins and pay 1 dollar if C loses. 2 Infinite Sample Spaces If a sample space has an infinite number of points, then the way that a distribution function is defined depends upon whether or not the sample space is countable. A sample space is countably infinite if the elements can be counted, i.e., can be put in one-to-one correspondence with the positive integers, and uncountably infinite
prob_Page_36_Chunk4875
1.2. DISCRETE PROBABILITY DISTRIBUTIONS 29 otherwise. Infinite sample spaces require new concepts in general (see Chapter 2), but countably infinite spaces do not. If Ω= {ω1, ω2, ω3, . . .} is a countably infinite sample space, then a distribution function is defined exactly as in Definition 1.2, except that the sum must now be a convergent infinite sum. Theorem 1.1 is still true, as are its extensions Theorems 1.2 and 1.4. One thing we cannot do on a countably infinite sample space that we could do on a finite sample space is to define a uniform distribution function as in Definition 1.3. You are asked in Exercise 20 to explain why this is not possible. Example 1.13 A coin is tossed until the first time that a head turns up. Let the outcome of the experiment, ω, be the first time that a head turns up. Then the possible outcomes of our experiment are Ω= {1, 2, 3, . . .} . Note that even though the coin could come up tails every time we have not allowed for this possibility. We will explain why in a moment. The probability that heads comes up on the first toss is 1/2. The probability that tails comes up on the first toss and heads on the second is 1/4. The probability that we have two tails followed by a head is 1/8, and so forth. This suggests assigning the distribution function m(n) = 1/2n for n = 1, 2, 3, . . . . To see that this is a distribution function we must show that X ω m(ω) = 1 2 + 1 4 + 1 8 + · · · = 1 . That this is true follows from the formula for the sum of a geometric series, 1 + r + r2 + r3 + · · · = 1 1 −r , or r + r2 + r3 + r4 + · · · = r 1 −r , (1.2) for −1 < r < 1. Putting r = 1/2, we see that we have a probability of 1 that the coin eventu- ally turns up heads. The possible outcome of tails every time has to be assigned probability 0, so we omit it from our sample space of possible outcomes. Let E be the event that the first time a head turns up is after an even number of tosses. Then E = {2, 4, 6, 8, . . .} , and P(E) = 1 4 + 1 16 + 1 64 + · · · . Putting r = 1/4 in Equation 1.2 see that P(E) = 1/4 1 −1/4 = 1 3 . Thus the probability that a head turns up for the first time after an even number of tosses is 1/3 and after an odd number of tosses is 2/3. 2
prob_Page_37_Chunk4876
30 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS Historical Remarks An interesting question in the history of science is: Why was probability not devel- oped until the sixteenth century? We know that in the sixteenth century problems in gambling and games of chance made people start to think about probability. But gambling and games of chance are almost as old as civilization itself. In ancient Egypt (at the time of the First Dynasty, ca. 3500 B.C.) a game now called “Hounds and Jackals” was played. In this game the movement of the hounds and jackals was based on the outcome of the roll of four-sided dice made out of animal bones called astragali. Six-sided dice made of a variety of materials date back to the sixteenth century B.C. Gambling was widespread in ancient Greece and Rome. Indeed, in the Roman Empire it was sometimes found necessary to invoke laws against gambling. Why, then, were probabilities not calculated until the sixteenth century? Several explanations have been advanced for this late development. One is that the relevant mathematics was not developed and was not easy to develop. The ancient mathematical notation made numerical calculation complicated, and our familiar algebraic notation was not developed until the sixteenth century. However, as we shall see, many of the combinatorial ideas needed to calculate probabilities were discussed long before the sixteenth century. Since many of the chance events of those times had to do with lotteries relating to religious affairs, it has been suggested that there may have been religious barriers to the study of chance and gambling. Another suggestion is that a stronger incentive, such as the development of commerce, was necessary. However, none of these explanations seems completely satisfactory, and people still wonder why it took so long for probability to be studied seriously. An interesting discussion of this problem can be found in Hacking.14 The first person to calculate probabilities systematically was Gerolamo Cardano (1501–1576) in his book Liber de Ludo Aleae. This was translated from the Latin by Gould and appears in the book Cardano: The Gambling Scholar by Ore.15 Ore provides a fascinating discussion of the life of this colorful scholar with accounts of his interests in many different fields, including medicine, astrology, and mathe- matics. You will also find there a detailed account of Cardano’s famous battle with Tartaglia over the solution to the cubic equation. In his book on probability Cardano dealt only with the special case that we have called the uniform distribution function. This restriction to equiprobable outcomes was to continue for a long time. In this case Cardano realized that the probability that an event occurs is the ratio of the number of favorable outcomes to the total number of outcomes. Many of Cardano’s examples dealt with rolling dice. Here he realized that the outcomes for two rolls should be taken to be the 36 ordered pairs (i, j) rather than the 21 unordered pairs. This is a subtle point that was still causing problems much later for other writers on probability. For example, in the eighteenth century the famous French mathematician d’Alembert, author of several works on probability, claimed that when a coin is tossed twice the number of heads that turn up would 14I. Hacking, The Emergence of Probability (Cambridge: Cambridge University Press, 1975). 15O. Ore, Cardano: The Gambling Scholar (Princeton: Princeton University Press, 1953).
prob_Page_38_Chunk4877
1.2. DISCRETE PROBABILITY DISTRIBUTIONS 31 be 0, 1, or 2, and hence we should assign equal probabilities for these three possible outcomes.16 Cardano chose the correct sample space for his dice problems and calculated the correct probabilities for a variety of events. Cardano’s mathematical work is interspersed with a lot of advice to the potential gambler in short paragraphs, entitled, for example: “Who Should Play and When,” “Why Gambling Was Condemned by Aristotle,” “Do Those Who Teach Also Play Well?” and so forth. In a paragraph entitled “The Fundamental Principle of Gam- bling,” Cardano writes: The most fundamental principle of all in gambling is simply equal con- ditions, e.g., of opponents, of bystanders, of money, of situation, of the dice box, and of the die itself. To the extent to which you depart from that equality, if it is in your opponent’s favor, you are a fool, and if in your own, you are unjust.17 Cardano did make mistakes, and if he realized it later he did not go back and change his error. For example, for an event that is favorable in three out of four cases, Cardano assigned the correct odds 3 : 1 that the event will occur. But then he assigned odds by squaring these numbers (i.e., 9 : 1) for the event to happen twice in a row. Later, by considering the case where the odds are 1 : 1, he realized that this cannot be correct and was led to the correct result that when f out of n outcomes are favorable, the odds for a favorable outcome twice in a row are f 2 : n2 −f 2. Ore points out that this is equivalent to the realization that if the probability that an event happens in one experiment is p, the probability that it happens twice is p2. Cardano proceeded to establish that for three successes the formula should be p3 and for four successes p4, making it clear that he understood that the probability is pn for n successes in n independent repetitions of such an experiment. This will follow from the concept of independence that we introduce in Section 4.1. Cardano’s work was a remarkable first attempt at writing down the laws of probability, but it was not the spark that started a systematic study of the subject. This came from a famous series of letters between Pascal and Fermat. This corre- spondence was initiated by Pascal to consult Fermat about problems he had been given by Chevalier de M´er´e, a well-known writer, a prominent figure at the court of Louis XIV, and an ardent gambler. The first problem de M´er´e posed was a dice problem. The story goes that he had been betting that at least one six would turn up in four rolls of a die and winning too often, so he then bet that a pair of sixes would turn up in 24 rolls of a pair of dice. The probability of a six with one die is 1/6 and, by the product law for independent experiments, the probability of two sixes when a pair of dice is thrown is (1/6)(1/6) = 1/36. Ore18 claims that a gambling rule of the time suggested that, since four repetitions was favorable for the occurrence of an event with probability 1/6, for an event six times as unlikely, 6 · 4 = 24 repetitions would be sufficient for 16J. d’Alembert, “Croix ou Pile,” in L’Encyclop´edie, ed. Diderot, vol. 4 (Paris, 1754). 17O. Ore, op. cit., p. 189. 18O. Ore, “Pascal and the Invention of Probability Theory,” American Mathematics Monthly, vol. 67 (1960), pp. 409–419.
prob_Page_39_Chunk4878
32 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS a favorable bet. Pascal showed, by exact calculation, that 25 rolls are required for a favorable bet for a pair of sixes. The second problem was a much harder one: it was an old problem and con- cerned the determination of a fair division of the stakes in a tournament when the series, for some reason, is interrupted before it is completed. This problem is now referred to as the problem of points. The problem had been a standard problem in mathematical texts; it appeared in Fra Luca Paccioli’s book summa de Arithmetica, Geometria, Proportioni et Proportionalit`a, printed in Venice in 1494,19 in the form: A team plays ball such that a total of 60 points are required to win the game, and each inning counts 10 points. The stakes are 10 ducats. By some incident they cannot finish the game and one side has 50 points and the other 20. One wants to know what share of the prize money belongs to each side. In this case I have found that opinions differ from one to another but all seem to me insufficient in their arguments, but I shall state the truth and give the correct way. Reasonable solutions, such as dividing the stakes according to the ratio of games won by each player, had been proposed, but no correct solution had been found at the time of the Pascal-Fermat correspondence. The letters deal mainly with the attempts of Pascal and Fermat to solve this problem. Blaise Pascal (1623–1662) was a child prodigy, having published his treatise on conic sections at age sixteen, and having invented a calculating machine at age eighteen. At the time of the letters, his demonstration of the weight of the atmosphere had already established his position at the forefront of contemporary physicists. Pierre de Fermat (1601– 1665) was a learned jurist in Toulouse, who studied mathematics in his spare time. He has been called by some the prince of amateurs and one of the greatest pure mathematicians of all times. The letters, translated by Maxine Merrington, appear in Florence David’s fasci- nating historical account of probability, Games, Gods and Gambling.20 In a letter dated Wednesday, 29th July, 1654, Pascal writes to Fermat: Sir, Like you, I am equally impatient, and although I am again ill in bed, I cannot help telling you that yesterday evening I received from M. de Carcavi your letter on the problem of points, which I admire more than I can possibly say. I have not the leisure to write at length, but, in a word, you have solved the two problems of points, one with dice and the other with sets of games with perfect justness; I am entirely satisfied with it for I do not doubt that I was in the wrong, seeing the admirable agreement in which I find myself with you now. . . Your method is very sound and is the one which first came to my mind in this research; but because the labour of the combination is excessive, I have found a short cut and indeed another method which is much 19ibid., p. 414. 20F. N. David, Games, Gods and Gambling (London: G. Griffin, 1962), p. 230 ff.
prob_Page_40_Chunk4879
1.2. DISCRETE PROBABILITY DISTRIBUTIONS 33 0 1 2 3 0 1 2 3 0 0 0 8 16 32 64 20 32 48 64 64 32 44 56 Number of games A has won Number of games B has won Figure 1.9: Pascal’s table. quicker and neater, which I would like to tell you here in a few words: for henceforth I would like to open my heart to you, if I may, as I am so overjoyed with our agreement. I see that truth is the same in Toulouse as in Paris. Here, more or less, is what I do to show the fair value of each game, when two opponents play, for example, in three games and each person has staked 32 pistoles. Let us say that the first man had won twice and the other once; now they play another game, in which the conditions are that, if the first wins, he takes all the stakes; that is 64 pistoles; if the other wins it, then they have each won two games, and therefore, if they wish to stop playing, they must each take back their own stake, that is, 32 pistoles each. Then consider, Sir, if the first man wins, he gets 64 pistoles; if he loses he gets 32. Thus if they do not wish to risk this last game but wish to separate without playing it, the first man must say: ‘I am certain to get 32 pistoles, even if I lost I still get them; but as for the other 32, perhaps I will get them, perhaps you will get them, the chances are equal. Let us then divide these 32 pistoles in half and give one half to me as well as my 32 which are mine for sure.’ He will then have 48 pistoles and the other 16.. . Pascal’s argument produces the table illustrated in Figure 1.9 for the amount due player A at any quitting point. Each entry in the table is the average of the numbers just above and to the right of the number. This fact, together with the known values when the tournament is completed, determines all the values in this table. If player A wins the first game,
prob_Page_41_Chunk4880
34 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS then he needs two games to win and B needs three games to win; and so, if the tounament is called off, A should receive 44 pistoles. The letter in which Fermat presented his solution has been lost; but fortunately, Pascal describes Fermat’s method in a letter dated Monday, 24th August, 1654. From Pascal’s letter:21 This is your procedure when there are two players: If two players, play- ing several games, find themselves in that position when the first man needs two games and second needs three, then to find the fair division of stakes, you say that one must know in how many games the play will be absolutely decided. It is easy to calculate that this will be in four games, from which you can conclude that it is necessary to see in how many ways four games can be arranged between two players, and one must see how many combinations would make the first man win and how many the second and to share out the stakes in this proportion. I would have found it difficult to understand this if I had not known it myself already; in fact you had explained it with this idea in mind. Fermat realized that the number of ways that the game might be finished may not be equally likely. For example, if A needs two more games and B needs three to win, two possible ways that the tournament might go for A to win are WLW and LWLW. These two sequences do not have the same chance of occurring. To avoid this difficulty, Fermat extended the play, adding fictitious plays, so that all the ways that the games might go have the same length, namely four. He was shrewd enough to realize that this extension would not change the winner and that he now could simply count the number of sequences favorable to each player since he had made them all equally likely. If we list all possible ways that the extended game of four plays might go, we obtain the following 16 possible outcomes of the play: WWWW WLWW LWWW LLWW WWWL WLWL LWWL LLWL WWLW WLLW LWLW LLLW WWLL WLLL LWLL LLLL . Player A wins in the cases where there are at least two wins (the 11 underlined cases), and B wins in the cases where there are at least three losses (the other 5 cases). Since A wins in 11 of the 16 possible cases Fermat argued that the probability that A wins is 11/16. If the stakes are 64 pistoles, A should receive 44 pistoles in agreement with Pascal’s result. Pascal and Fermat developed more systematic methods for counting the number of favorable outcomes for problems like this, and this will be one of our central problems. Such counting methods fall under the subject of combinatorics, which is the topic of Chapter 3. 21ibid., p. 239ff.
prob_Page_42_Chunk4881
1.2. DISCRETE PROBABILITY DISTRIBUTIONS 35 We see that these two mathematicians arrived at two very different ways to solve the problem of points. Pascal’s method was to develop an algorithm and use it to calculate the fair division. This method is easy to implement on a computer and easy to generalize. Fermat’s method, on the other hand, was to change the problem into an equivalent problem for which he could use counting or combinatorial methods. We will see in Chapter 3 that, in fact, Fermat used what has become known as Pascal’s triangle! In our study of probability today we shall find that both the algorithmic approach and the combinatorial approach share equal billing, just as they did 300 years ago when probability got its start. Exercises 1 Let Ω= {a, b, c} be a sample space. Let m(a) = 1/2, m(b) = 1/3, and m(c) = 1/6. Find the probabilities for all eight subsets of Ω. 2 Give a possible sample space Ωfor each of the following experiments: (a) An election decides between two candidates A and B. (b) A two-sided coin is tossed. (c) A student is asked for the month of the year and the day of the week on which her birthday falls. (d) A student is chosen at random from a class of ten students. (e) You receive a grade in this course. 3 For which of the cases in Exercise 2 would it be reasonable to assign the uniform distribution function? 4 Describe in words the events specified by the following subsets of Ω= {HHH, HHT, HTH, HTT, THH, THT, TTH, TTT} (see Example 1.6). (a) E = {HHH,HHT,HTH,HTT}. (b) E = {HHH,TTT}. (c) E = {HHT,HTH,THH}. (d) E = {HHT,HTH,HTT,THH,THT,TTH,TTT}. 5 What are the probabilities of the events described in Exercise 4? 6 A die is loaded in such a way that the probability of each face turning up is proportional to the number of dots on that face. (For example, a six is three times as probable as a two.) What is the probability of getting an even number in one throw? 7 Let A and B be events such that P(A ∩B) = 1/4, P( ˜A) = 1/3, and P(B) = 1/2. What is P(A ∪B)?
prob_Page_43_Chunk4882
36 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS 8 A student must choose one of the subjects, art, geology, or psychology, as an elective. She is equally likely to choose art or psychology and twice as likely to choose geology. What are the respective probabilities that she chooses art, geology, and psychology? 9 A student must choose exactly two out of three electives: art, French, and mathematics. He chooses art with probability 5/8, French with probability 5/8, and art and French together with probability 1/4. What is the probability that he chooses mathematics? What is the probability that he chooses either art or French? 10 For a bill to come before the president of the United States, it must be passed by both the House of Representatives and the Senate. Assume that, of the bills presented to these two bodies, 60 percent pass the House, 80 percent pass the Senate, and 90 percent pass at least one of the two. Calculate the probability that the next bill presented to the two groups will come before the president. 11 What odds should a person give in favor of the following events? (a) A card chosen at random from a 52-card deck is an ace. (b) Two heads will turn up when a coin is tossed twice. (c) Boxcars (two sixes) will turn up when two dice are rolled. 12 You offer 3 : 1 odds that your friend Smith will be elected mayor of your city. What probability are you assigning to the event that Smith wins? 13 In a horse race, the odds that Romance will win are listed as 2 : 3 and that Downhill will win are 1 : 2. What odds should be given for the event that either Romance or Downhill wins? 14 Let X be a random variable with distribution function mX(x) defined by mX(−1) = 1/5, mX(0) = 1/5, mX(1) = 2/5, mX(2) = 1/5 . (a) Let Y be the random variable defined by the equation Y = X + 3. Find the distribution function mY (y) of Y . (b) Let Z be the random variable defined by the equation Z = X 2. Find the distribution function mZ(z) of Z. *15 John and Mary are taking a mathematics course. The course has only three grades: A, B, and C. The probability that John gets a B is .3. The probability that Mary gets a B is .4. The probability that neither gets an A but at least one gets a B is .1. What is the probability that at least one gets a B but neither gets a C? 16 In a fierce battle, not less than 70 percent of the soldiers lost one eye, not less than 75 percent lost one ear, not less than 80 percent lost one hand, and not
prob_Page_44_Chunk4883
1.2. DISCRETE PROBABILITY DISTRIBUTIONS 37 less than 85 percent lost one leg. What is the minimal possible percentage of those who simultaneously lost one ear, one eye, one hand, and one leg?22 *17 Assume that the probability of a “success” on a single experiment with n outcomes is 1/n. Let m be the number of experiments necessary to make it a favorable bet that at least one success will occur (see Exercise 1.1.5). (a) Show that the probability that, in m trials, there are no successes is (1 −1/n)m. (b) (de Moivre) Show that if m = n log 2 then lim n→∞  1 −1 n m = 1 2 . Hint: lim n→∞  1 −1 n n = e−1 . Hence for large n we should choose m to be about n log 2. (c) Would DeMoivre have been led to the correct answer for de M´er´e’s two bets if he had used his approximation? 18 (a) For events A1, . . . , An, prove that P(A1 ∪· · · ∪An) ≤P(A1) + · · · + P(An) . (b) For events A and B, prove that P(A ∩B) ≥P(A) + P(B) −1. 19 If A, B, and C are any three events, show that P(A ∪B ∪C) = P(A) + P(B) + P(C) −P(A ∩B) −P(B ∩C) −P(C ∩A) + P(A ∩B ∩C) . 20 Explain why it is not possible to define a uniform distribution function (see Definition 1.3) on a countably infinite sample space. Hint: Assume m(ω) = a for all ω, where 0 ≤a ≤1. Does m(ω) have all the properties of a distribution function? 21 In Example 1.13 find the probability that the coin turns up heads for the first time on the tenth, eleventh, or twelfth toss. 22 A die is rolled until the first time that a six turns up. We shall see that the probability that this occurs on the nth roll is (5/6)n−1 ·(1/6). Using this fact, describe the appropriate infinite sample space and distribution function for the experiment of rolling a die until a six turns up for the first time. Verify that for your distribution function P ω m(ω) = 1. 22See Knot X, in Lewis Carroll, Mathematical Recreations, vol. 2 (Dover, 1958).
prob_Page_45_Chunk4884
38 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS 23 Let Ωbe the sample space Ω= {0, 1, 2, . . .} , and define a distribution function by m(j) = (1 −r)jr , for some fixed r, 0 < r < 1, and for j = 0, 1, 2, . . .. Show that this is a distribution function for Ω. 24 Our calendar has a 400-year cycle. B. H. Brown noticed that the number of times the thirteenth of the month falls on each of the days of the week in the 4800 months of a cycle is as follows: Sunday 687 Monday 685 Tuesday 685 Wednesday 687 Thursday 684 Friday 688 Saturday 684 From this he deduced that the thirteenth was more likely to fall on Friday than on any other day. Explain what he meant by this. 25 Tversky and Kahneman23 asked a group of subjects to carry out the following task. They are told that: Linda is 31, single, outspoken, and very bright. She majored in philosophy in college. As a student, she was deeply concerned with racial discrimination and other social issues, and participated in anti-nuclear demonstrations. The subjects are then asked to rank the likelihood of various alternatives, such as: (1) Linda is active in the feminist movement. (2) Linda is a bank teller. (3) Linda is a bank teller and active in the feminist movement. Tversky and Kahneman found that between 85 and 90 percent of the subjects rated alternative (1) most likely, but alternative (3) more likely than alterna- tive (2). Is it? They call this phenomenon the conjunction fallacy, and note that it appears to be unaffected by prior training in probability or statistics. Is this phenomenon a fallacy? If so, why? Can you give a possible explanation for the subjects’ choices? 23K. McKean, “Decisions, Decisions,” pp. 22–31.
prob_Page_46_Chunk4885
1.2. DISCRETE PROBABILITY DISTRIBUTIONS 39 26 Two cards are drawn successively from a deck of 52 cards. Find the probability that the second card is higher in rank than the first card. Hint: Show that 1 = P(higher) + P(lower) + P(same) and use the fact that P(higher) = P(lower). 27 A life table is a table that lists for a given number of births the estimated number of people who will live to a given age. In Appendix C we give a life table based upon 100,000 births for ages from 0 to 85, both for women and for men. Show how from this table you can estimate the probability m(x) that a person born in 1981 would live to age x. Write a program to plot m(x) both for men and for women, and comment on the differences that you see in the two cases. *28 Here is an attempt to get around the fact that we cannot choose a “random integer.” (a) What, intuitively, is the probability that a “randomly chosen” positive integer is a multiple of 3? (b) Let P3(N) be the probability that an integer, chosen at random between 1 and N, is a multiple of 3 (since the sample space is finite, this is a legitimate probability). Show that the limit P3 = lim N→∞P3(N) exists and equals 1/3. This formalizes the intuition in (a), and gives us a way to assign “probabilities” to certain events that are infinite subsets of the positive integers. (c) If A is any set of positive integers, let A(N) mean the number of elements of A which are less than or equal to N. Then define the “probability” of A as P(A) = lim N→∞A(N)/N , provided this limit exists. Show that this definition would assign prob- ability 0 to any finite set and probability 1 to the set of all positive integers. Thus, the probability of the set of all integers is not the sum of the probabilities of the individual integers in this set. This means that the definition of probability given here is not a completely satisfactory definition. (d) Let A be the set of all positive integers with an odd number of dig- its. Show that P(A) does not exist. This shows that under the above definition of probability, not all sets have probabilities. 29 (from Sholander24) In a standard clover-leaf interchange, there are four ramps for making right-hand turns, and inside these four ramps, there are four more ramps for making left-hand turns. Your car approaches the interchange from the south. A mechanism has been installed so that at each point where there exists a choice of directions, the car turns to the right with fixed probability r. 24M. Sholander, Problem #1034, Mathematics Magazine, vol. 52, no. 3 (May 1979), p. 183.
prob_Page_47_Chunk4886
40 CHAPTER 1. DISCRETE PROBABILITY DISTRIBUTIONS (a) If r = 1/2, what is your chance of emerging from the interchange going west? (b) Find the value of r that maximizes your chance of a westward departure from the interchange. 30 (from Benkoski25) Consider a “pure” cloverleaf interchange in which there are no ramps for right-hand turns, but only the two intersecting straight highways with cloverleaves for left-hand turns. (Thus, to turn right in such an interchange, one must make three left-hand turns.) As in the preceding problem, your car approaches the interchange from the south. What is the value of r that maximizes your chances of an eastward departure from the interchange? 31 (from vos Savant26) A reader of Marilyn vos Savant’s column wrote in with the following question: My dad heard this story on the radio. At Duke University, two students had received A’s in chemistry all semester. But on the night before the final exam, they were partying in another state and didn’t get back to Duke until it was over. Their excuse to the professor was that they had a flat tire, and they asked if they could take a make-up test. The professor agreed, wrote out a test and sent the two to separate rooms to take it. The first question (on one side of the paper) was worth 5 points, and they answered it easily. Then they flipped the paper over and found the second question, worth 95 points: ‘Which tire was it?’ What was the probability that both students would say the same thing? My dad and I think it’s 1 in 16. Is that right?” (a) Is the answer 1/16? (b) The following question was asked of a class of students. “I was driving to school today, and one of my tires went flat. Which tire do you think it was?” The responses were as follows: right front, 58%, left front, 11%, right rear, 18%, left rear, 13%. Suppose that this distribution holds in the general population, and assume that the two test-takers are randomly chosen from the general population. What is the probability that they will give the same answer to the second question? 25S. Benkoski, Comment on Problem #1034, Mathematics Magazine, vol. 52, no. 3 (May 1979), pp. 183-184. 26M. vos Savant, Parade Magazine, 3 March 1996, p. 14.
prob_Page_48_Chunk4887
Chapter 2 Continuous Probability Densities 2.1 Simulation of Continuous Probabilities In this section we shall show how we can use computer simulations for experiments that have a whole continuum of possible outcomes. Probabilities Example 2.1 We begin by constructing a spinner, which consists of a circle of unit circumference and a pointer as shown in Figure 2.1. We pick a point on the circle and label it 0, and then label every other point on the circle with the distance, say x, from 0 to that point, measured counterclockwise. The experiment consists of spinning the pointer and recording the label of the point at the tip of the pointer. We let the random variable X denote the value of this outcome. The sample space is clearly the interval [0, 1). We would like to construct a probability model in which each outcome is equally likely to occur. If we proceed as we did in Chapter 1 for experiments with a finite number of possible outcomes, then we must assign the probability 0 to each outcome, since otherwise, the sum of the probabilities, over all of the possible outcomes, would not equal 1. (In fact, summing an uncountable number of real numbers is a tricky business; in particular, in order for such a sum to have any meaning, at most countably many of the summands can be different than 0.) However, if all of the assigned probabilities are 0, then the sum is 0, not 1, as it should be. In the next section, we will show how to construct a probability model in this situation. At present, we will assume that such a model can be constructed. We will also assume that in this model, if E is an arc of the circle, and E is of length p, then the model will assign the probability p to E. This means that if the pointer is spun, the probability that it ends up pointing to a point in E equals p, which is certainly a reasonable thing to expect. 41
prob_Page_49_Chunk4888
42 CHAPTER 2. CONTINUOUS PROBABILITY DENSITIES 0 x Figure 2.1: A spinner. To simulate this experiment on a computer is an easy matter. Many computer software packages have a function which returns a random real number in the in- terval [0, 1]. Actually, the returned value is always a rational number, and the values are determined by an algorithm, so a sequence of such values is not truly random. Nevertheless, the sequences produced by such algorithms behave much like theoretically random sequences, so we can use such sequences in the simulation of experiments. On occasion, we will need to refer to such a function. We will call this function rnd. 2 Monte Carlo Procedure and Areas It is sometimes desirable to estimate quantities whose exact values are difficult or impossible to calculate exactly. In some of these cases, a procedure involving chance, called a Monte Carlo procedure, can be used to provide such an estimate. Example 2.2 In this example we show how simulation can be used to estimate areas of plane figures. Suppose that we program our computer to provide a pair (x, y) or numbers, each chosen independently at random from the interval [0, 1]. Then we can interpret this pair (x, y) as the coordinates of a point chosen at random from the unit square. Events are subsets of the unit square. Our experience with Example 2.1 suggests that the point is equally likely to fall in subsets of equal area. Since the total area of the square is 1, the probability of the point falling in a specific subset E of the unit square should be equal to its area. Thus, we can estimate the area of any subset of the unit square by estimating the probability that a point chosen at random from this square falls in the subset. We can use this method to estimate the area of the region E under the curve y = x2 in the unit square (see Figure 2.2). We choose a large number of points (x, y) at random and record what fraction of them fall in the region E = { (x, y) : y ≤x2 }. The program MonteCarlo will carry out this experiment for us. Running this program for 10,000 experiments gives an estimate of .325 (see Figure 2.3). From these experiments we would estimate the area to be about 1/3. Of course,
prob_Page_50_Chunk4889
2.1. SIMULATION OF CONTINUOUS PROBABILITIES 43 1 x 1 y y = x2 E Figure 2.2: Area under y = x2. for this simple region we can find the exact area by calculus. In fact, Area of E = Z 1 0 x2 dx = 1 3 . We have remarked in Chapter 1 that, when we simulate an experiment of this type n times to estimate a probability, we can expect the answer to be in error by at most 1/√n at least 95 percent of the time. For 10,000 experiments we can expect an accuracy of 0.01, and our simulation did achieve this accuracy. This same argument works for any region E of the unit square. For example, suppose E is the circle with center (1/2, 1/2) and radius 1/2. Then the probability that our random point (x, y) lies inside the circle is equal to the area of the circle, that is, P(E) = π 1 2 2 = π 4 . If we did not know the value of π, we could estimate the value by performing this experiment a large number of times! 2 The above example is not the only way of estimating the value of π by a chance experiment. Here is another way, discovered by Buffon.1 1G. L. Buffon, in “Essai d’Arithm´etique Morale,” Oeuvres Compl`etes de Buffon avec Supple- ments, tome iv, ed. Dum´enil (Paris, 1836).
prob_Page_51_Chunk4890
44 CHAPTER 2. CONTINUOUS PROBABILITY DENSITIES 1 1 1000 trials Estimate of area is .325 y = x2 E Figure 2.3: Computing the area by simulation. Buffon’s Needle Example 2.3 Suppose that we take a card table and draw across the top surface a set of parallel lines a unit distance apart. We then drop a common needle of unit length at random on this surface and observe whether or not the needle lies across one of the lines. We can describe the possible outcomes of this experiment by coordinates as follows: Let d be the distance from the center of the needle to the nearest line. Next, let L be the line determined by the needle, and define θ as the acute angle that the line L makes with the set of parallel lines. (The reader should certainly be wary of this description of the sample space. We are attempting to coordinatize a set of line segments. To see why one must be careful in the choice of coordinates, see Example 2.6.) Using this description, we have 0 ≤d ≤1/2, and 0 ≤θ ≤π/2. Moreover, we see that the needle lies across the nearest line if and only if the hypotenuse of the triangle (see Figure 2.4) is less than half the length of the needle, that is, d sin θ < 1 2 . Now we assume that when the needle drops, the pair (θ, d) is chosen at random from the rectangle 0 ≤θ ≤π/2, 0 ≤d ≤1/2. We observe whether the needle lies across the nearest line (i.e., whether d ≤(1/2) sin θ). The probability of this event E is the fraction of the area of the rectangle which lies inside E (see Figure 2.5).
prob_Page_52_Chunk4891
2.1. SIMULATION OF CONTINUOUS PROBABILITIES 45 d 1/2 θ Figure 2.4: Buffon’s experiment. θ 0 1/2 0 d π/2 E Figure 2.5: Set E of pairs (θ, d) with d < 1 2 sin θ. Now the area of the rectangle is π/4, while the area of E is Area = Z π/2 0 1 2 sin θ dθ = 1 2 . Hence, we get P(E) = 1/2 π/4 = 2 π . The program BuffonsNeedle simulates this experiment. In Figure 2.6, we show the position of every 100th needle in a run of the program in which 10,000 needles were “dropped.” Our final estimate for π is 3.139. While this was within 0.003 of the true value for π we had no right to expect such accuracy. The reason for this is that our simulation estimates P(E). While we can expect this estimate to be in error by at most 0.001, a small error in P(E) gets magnified when we use this to compute π = 2/P(E). Perlman and Wichura, in their article “Sharpening Buffon’s
prob_Page_53_Chunk4892
46 CHAPTER 2. CONTINUOUS PROBABILITY DENSITIES 0.00 5.00 0.50 1.00 1.50 2.00 2.50 3.00 3.50 4.00 4.50 5.00 10000 3.139 Figure 2.6: Simulation of Buffon’s needle experiment. Needle,”2 show that we can expect to have an error of not more than 5/√n about 95 percent of the time. Here n is the number of needles dropped. Thus for 10,000 needles we should expect an error of no more than 0.05, and that was the case here. We see that a large number of experiments is necessary to get a decent estimate for π. 2 In each of our examples so far, events of the same size are equally likely. Here is an example where they are not. We will see many other such examples later. Example 2.4 Suppose that we choose two random real numbers in [0, 1] and add them together. Let X be the sum. How is X distributed? To help understand the answer to this question, we can use the program Are- abargraph. This program produces a bar graph with the property that on each interval, the area, rather than the height, of the bar is equal to the fraction of out- comes that fell in the corresponding interval. We have carried out this experiment 1000 times; the data is shown in Figure 2.7. It appears that the function defined by f(x) =  x, if 0 ≤x ≤1, 2 −x, if 1 < x ≤2 fits the data very well. (It is shown in the figure.) In the next section, we will see that this function is the “right” function. By this we mean that if a and b are any two real numbers between 0 and 2, with a ≤b, then we can use this function to calculate the probability that a ≤X ≤b. To understand how this calculation might be performed, we again consider Figure 2.7. Because of the way the bars were constructed, the sum of the areas of the bars corresponding to the interval 2M. D. Perlman and M. J. Wichura, “Sharpening Buffon’s Needle,” The American Statistician, vol. 29, no. 4 (1975), pp. 157–163.
prob_Page_54_Chunk4893
2.1. SIMULATION OF CONTINUOUS PROBABILITIES 47 0 0.5 1 1.5 2 0 0.2 0.4 0.6 0.8 1 Figure 2.7: Sum of two random numbers. [a, b] approximates the probability that a ≤X ≤b. But the sum of the areas of these bars also approximates the integral Z b a f(x) dx . This suggests that for an experiment with a continuum of possible outcomes, if we find a function with the above property, then we will be able to use it to calculate probabilities. In the next section, we will show how to determine the function f(x). 2 Example 2.5 Suppose that we choose 100 random numbers in [0, 1], and let X represent their sum. How is X distributed? We have carried out this experiment 10000 times; the results are shown in Figure 2.8. It is not so clear what function fits the bars in this case. It turns out that the type of function which does the job is called a normal density function. This type of function is sometimes referred to as a “bell-shaped” curve. It is among the most important functions in the subject of probability, and will be formally defined in Section 5.2 of Chapter 4.3. 2 Our last example explores the fundamental question of how probabilities are assigned. Bertrand’s Paradox Example 2.6 A chord of a circle is a line segment both of whose endpoints lie on the circle. Suppose that a chord is drawn at random in a unit circle. What is the probability that its length exceeds √ 3? Our answer will depend on what we mean by random, which will depend, in turn, on what we choose for coordinates. The sample space Ωis the set of all possible chords in the circle. To find coordinates for these chords, we first introduce a
prob_Page_55_Chunk4894
48 CHAPTER 2. CONTINUOUS PROBABILITY DENSITIES 40 45 50 55 60 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 Figure 2.8: Sum of 100 random numbers. x y A B M θ β α Figure 2.9: Random chord. rectangular coordinate system with origin at the center of the circle (see Figure 2.9). We note that a chord of a circle is perpendicular to the radial line containing the midpoint of the chord. We can describe each chord by giving: 1. The rectangular coordinates (x, y) of the midpoint M, or 2. The polar coordinates (r, θ) of the midpoint M, or 3. The polar coordinates (1, α) and (1, β) of the endpoints A and B. In each case we shall interpret at random to mean: choose these coordinates at random. We can easily estimate this probability by computer simulation. In programming this simulation, it is convenient to include certain simplifications, which we describe in turn:
prob_Page_56_Chunk4895
2.1. SIMULATION OF CONTINUOUS PROBABILITIES 49 1. To simulate this case, we choose values for x and y from [−1, 1] at random. Then we check whether x2 + y2 ≤1. If not, the point M = (x, y) lies outside the circle and cannot be the midpoint of any chord, and we ignore it. Oth- erwise, M lies inside the circle and is the midpoint of a unique chord, whose length L is given by the formula: L = 2 p 1 −(x2 + y2) . 2. To simulate this case, we take account of the fact that any rotation of the circle does not change the length of the chord, so we might as well assume in advance that the chord is horizontal. Then we choose r from [−1, 1] at random, and compute the length of the resulting chord with midpoint (r, π/2) by the formula: L = 2 p 1 −r2 . 3. To simulate this case, we assume that one endpoint, say B, lies at (1, 0) (i.e., that β = 0). Then we choose a value for α from [0, 2π] at random and compute the length of the resulting chord, using the Law of Cosines, by the formula: L = √ 2 −2 cos α . The program BertrandsParadox carries out this simulation. Running this program produces the results shown in Figure 2.10. In the first circle in this figure, a smaller circle has been drawn. Those chords which intersect this smaller circle have length at least √ 3. In the second circle in the figure, the vertical line intersects all chords of length at least √ 3. In the third circle, again the vertical line intersects all chords of length at least √ 3. In each case we run the experiment a large number of times and record the fraction of these lengths that exceed √ 3. We have printed the results of every 100th trial up to 10,000 trials. It is interesting to observe that these fractions are not the same in the three cases; they depend on our choice of coordinates. This phenomenon was first observed by Bertrand, and is now known as Bertrand’s paradox.3 It is actually not a paradox at all; it is merely a reflection of the fact that different choices of coordinates will lead to different assignments of probabilities. Which assignment is “correct” depends on what application or interpretation of the model one has in mind. One can imagine a real experiment involving throwing long straws at a circle drawn on a card table. A “correct” assignment of coordinates should not depend on where the circle lies on the card table, or where the card table sits in the room. Jaynes4 has shown that the only assignment which meets this requirement is (2). In this sense, the assignment (2) is the natural, or “correct” one (see Exercise 11). We can easily see in each case what the true probabilities are if we note that √ 3 is the length of the side of an inscribed equilateral triangle. Hence, a chord has 3J. Bertrand, Calcul des Probabilit´es (Paris: Gauthier-Villars, 1889). 4E. T. Jaynes, “The Well-Posed Problem,” in Papers on Probability, Statistics and Statistical Physics, R. D. Rosencrantz, ed. (Dordrecht: D. Reidel, 1983), pp. 133–148.
prob_Page_57_Chunk4896
50 CHAPTER 2. CONTINUOUS PROBABILITY DENSITIES .0 1.0 .2 .4 .6 .8 1.0 .488 .227 .0 1.0 .2 .4 .6 .8 1.0 .0 1.0 .2 .4 .6 .8 1.0 .332 10000 10000 10000 Figure 2.10: Bertrand’s paradox. length L > √ 3 if its midpoint has distance d < 1/2 from the origin (see Figure 2.9). The following calculations determine the probability that L > √ 3 in each of the three cases. 1. L > √ 3 if(x, y) lies inside a circle of radius 1/2, which occurs with probability p = π(1/2)2 π(1)2 = 1 4 . 2. L > √ 3 if |r| < 1/2, which occurs with probability 1/2 −(−1/2) 1 −(−1) = 1 2 . 3. L > √ 3 if 2π/3 < α < 4π/3, which occurs with probability 4π/3 −2π/3 2π −0 = 1 3 . We see that our simulations agree quite well with these theoretical values. 2 Historical Remarks G. L. Buffon (1707–1788) was a natural scientist in the eighteenth century who applied probability to a number of his investigations. His work is found in his monumental 44-volume Histoire Naturelle and its supplements.5 For example, he 5G. L. Buffon, Histoire Naturelle, Generali et Particular avec le Descripti´on du Cabinet du Roy, 44 vols. (Paris: L‘Imprimerie Royale, 1749–1803).
prob_Page_58_Chunk4897
2.1. SIMULATION OF CONTINUOUS PROBABILITIES 51 Length of Number of Number of Estimate Experimenter needle casts crossings for π Wolf, 1850 .8 5000 2532 3.1596 Smith, 1855 .6 3204 1218.5 3.1553 De Morgan, c.1860 1.0 600 382.5 3.137 Fox, 1864 .75 1030 489 3.1595 Lazzerini, 1901 .83 3408 1808 3.1415929 Reina, 1925 .5419 2520 869 3.1795 Table 2.1: Buffon needle experiments to estimate π. presented a number of mortality tables and used them to compute, for each age group, the expected remaining lifetime. From his table he observed: the expected remaining lifetime of an infant of one year is 33 years, while that of a man of 21 years is also approximately 33 years. Thus, a father who is not yet 21 can hope to live longer than his one year old son, but if the father is 40, the odds are already 3 to 2 that his son will outlive him.6 Buffon wanted to show that not all probability calculations rely only on algebra, but that some rely on geometrical calculations. One such problem was his famous “needle problem” as discussed in this chapter.7 In his original formulation, Buffon describes a game in which two gamblers drop a loaf of French bread on a wide-board floor and bet on whether or not the loaf falls across a crack in the floor. Buffon asked: what length L should the bread loaf be, relative to the width W of the floorboards, so that the game is fair. He found the correct answer (L = (π/4)W) using essentially the methods described in this chapter. He also considered the case of a checkerboard floor, but gave the wrong answer in this case. The correct answer was given later by Laplace. The literature contains descriptions of a number of experiments that were actu- ally carried out to estimate π by this method of dropping needles. N. T. Gridgeman8 discusses the experiments shown in Table 2.1. (The halves for the number of cross- ing comes from a compromise when it could not be decided if a crossing had actually occurred.) He observes, as we have, that 10,000 casts could do no more than estab- lish the first decimal place of π with reasonable confidence. Gridgeman points out that, although none of the experiments used even 10,000 casts, they are surprisingly good, and in some cases, too good. The fact that the number of casts is not always a round number would suggest that the authors might have resorted to clever stop- ping to get a good answer. Gridgeman comments that Lazzerini’s estimate turned out to agree with a well-known approximation to π, 355/113 = 3.1415929, discov- ered by the fifth-century Chinese mathematician, Tsu Ch’ungchih. Gridgeman says that he did not have Lazzerini’s original report, and while waiting for it (knowing 6G. L. Buffon, “Essai d’Arithm´etique Morale,” p. 301. 7ibid., pp. 277–278. 8N. T. Gridgeman, “Geometric Probability and the Number π” Scripta Mathematika, vol. 25, no. 3, (1960), pp. 183–195.
prob_Page_59_Chunk4898
52 CHAPTER 2. CONTINUOUS PROBABILITY DENSITIES only the needle crossed a line 1808 times in 3408 casts) deduced that the length of the needle must have been 5/6. He calculated this from Buffon’s formula, assuming π = 355/113: L = πP(E) 2 = 1 2 355 113  1808 3408  = 5 6 = .8333 . Even with careful planning one would have to be extremely lucky to be able to stop so cleverly. The second author likes to trace his interest in probability theory to the Chicago World’s Fair of 1933 where he observed a mechanical device dropping needles and displaying the ever-changing estimates for the value of π. (The first author likes to trace his interest in probability theory to the second author.) Exercises *1 In the spinner problem (see Example 2.1) divide the unit circumference into three arcs of length 1/2, 1/3, and 1/6. Write a program to simulate the spinner experiment 1000 times and print out what fraction of the outcomes fall in each of the three arcs. Now plot a bar graph whose bars have width 1/2, 1/3, and 1/6, and areas equal to the corresponding fractions as determined by your simulation. Show that the heights of the bars are all nearly the same. 2 Do the same as in Exercise 1, but divide the unit circumference into five arcs of length 1/3, 1/4, 1/5, 1/6, and 1/20. 3 Alter the program MonteCarlo to estimate the area of the circle of radius 1/2 with center at (1/2, 1/2) inside the unit square by choosing 1000 points at random. Compare your results with the true value of π/4. Use your results to estimate the value of π. How accurate is your estimate? 4 Alter the program MonteCarlo to estimate the area under the graph of y = sin πx inside the unit square by choosing 10,000 points at random. Now calculate the true value of this area and use your results to estimate the value of π. How accurate is your estimate? 5 Alter the program MonteCarlo to estimate the area under the graph of y = 1/(x + 1) in the unit square in the same way as in Exercise 4. Calculate the true value of this area and use your simulation results to estimate the value of log 2. How accurate is your estimate? 6 To simulate the Buffon’s needle problem we choose independently the dis- tance d and the angle θ at random, with 0 ≤d ≤1/2 and 0 ≤θ ≤π/2, and check whether d ≤(1/2) sinθ. Doing this a large number of times, we estimate π as 2/a, where a is the fraction of the times that d ≤(1/2) sin θ. Write a program to estimate π by this method. Run your program several times for each of 100, 1000, and 10,000 experiments. Does the accuracy of the experimental approximation for π improve as the number of experiments increases?
prob_Page_60_Chunk4899
2.1. SIMULATION OF CONTINUOUS PROBABILITIES 53 7 For Buffon’s needle problem, Laplace9 considered a grid with horizontal and vertical lines one unit apart. He showed that the probability that a needle of length L ≤1 crosses at least one line is p = 4L −L2 π . To simulate this experiment we choose at random an angle θ between 0 and π/2 and independently two numbers d1 and d2 between 0 and L/2. (The two numbers represent the distance from the center of the needle to the nearest horizontal and vertical line.) The needle crosses a line if either d1 ≤(L/2) sin θ or d2 ≤(L/2) cosθ. We do this a large number of times and estimate π as ¯π = 4L −L2 a , where a is the proportion of times that the needle crosses at least one line. Write a program to estimate π by this method, run your program for 100, 1000, and 10,000 experiments, and compare your results with Buffon’s method described in Exercise 6. (Take L = 1.) 8 A long needle of length L much bigger than 1 is dropped on a grid with horizontal and vertical lines one unit apart. We will see (in Exercise 6.3.28) that the average number a of lines crossed is approximately a = 4L π . To estimate π by simulation, pick an angle θ at random between 0 and π/2 and compute L sin θ + L cos θ. This may be used for the number of lines crossed. Repeat this many times and estimate π by ¯π = 4L a , where a is the average number of lines crossed per experiment. Write a pro- gram to simulate this experiment and run your program for the number of experiments equal to 100, 1000, and 10,000. Compare your results with the methods of Laplace or Buffon for the same number of experiments. (Use L = 100.) The following exercises involve experiments in which not all outcomes are equally likely. We shall consider such experiments in detail in the next section, but we invite you to explore a few simple cases here. 9 A large number of waiting time problems have an exponential distribution of outcomes. We shall see (in Section 5.2) that such outcomes are simulated by computing (−1/λ) log(rnd), where λ > 0. For waiting times produced in this way, the average waiting time is 1/λ. For example, the times spent waiting for 9P. S. Laplace, Th´eorie Analytique des Probabilit´es (Paris: Courcier, 1812).
prob_Page_61_Chunk4900