text
stringlengths
1
7.76k
source
stringlengths
17
81
12.1. TRAVELING WAVES 285 Comparing (12.7) and (12.8), you can see that E V = cp V (12.9) This relationship between the energy and momentum densities (one is just c times the other) is an extremely general result that applies to all sorts of waves, including electromagnetic waves! 12.1.3 The wave velocity You may ask, what determines the speed of a wave in a material medium? The answer, qualitatively speaking, is that c always ends up being something of the form c ∼ * stiffness inertia (12.10) where “stiffness” is some measure of how rigid the material is (how hard it is to compress it or, in the case of a transverse wave, shear it), whereas “inertia” means some sort of mass density. For a transverse wave on a string, for instance, we find c = . F t µ (12.11) where F t is the tension in the string and µ is not the “reduced mass” of anything (sorry about the confusion!), but a common way to write the “mass per unit length” of the string. We could also just write µ = M/L, where M is the total mass of the string and L its length. Note that the tension is a measure of the stiffness of the string, so this is, indeed, of the general form (12.10). For two strings under the same tension, but with different densities, the wave will travel more slowly on the denser one. For a sound wave in a fluid (liquid or gas), the speed of sound is usually written c = . B ρ0 (12.12) where ρ0 is the regular density (mass per unit volume), and B is the so-called bulk modulus, which gives the fluid’s resistance to a change in volume when a pressure P is applied to it: B = P/(∆V/V ). So, once again, we get something of the form (12.10). In this case, however, we find that for many fluids the density and the stiffness are linked, so they increase together, which means we cannot simply assume that the speed of sound will be automatically smaller in a denser medium. For gases, this does work well: the speed of sound in a lighter gas, like helium, is greater than in air,
University Physics I Classical Mechanics_Page_303_Chunk4501
286 CHAPTER 12. WAVES IN ONE DIMENSION whereas in a denser gas like sulfur hexafluoride the speed of sound is less than in air1. However, if you compare the speed of sound in water to the speed of sound in air, you find it is much greater in water, since water is much harder to compress than air: in this case, the increase in stiffness more than makes up for the increase in density. The same thing happens if you go from a liquid like water to a solid, where the speed of sound is given by c = . Y ρ0 (12.13) where Y is, again, a measure of the stiffness of the material, called the Young modulus. Since a solid is typically even harder to compress than a liquid, the speed of sound in solids such as metals is much greater than in water, despite their being also denser. For reference, the speed of sound in steel would be about c = 5, 000 m/s; in water, about 1, 500 m/s; and in air, “only” about 340 m/s. 12.1.4 Reflection and transmission of waves at a medium boundary Suppose that you have two different elastic media, joined in some way at a common boundary, and you have a wave in the first medium traveling towards the boundary. Examples of media connected this way could be two different strings tied together, or two springs with different spring constants joined at the ends; or, for sound waves, it could just be something like water with air above it: a compression wave in air traveling towards the water surface will push on the surface and set up a sound wave there, and vice-versa. The first thing to notice is that, if the incident wave has a frequency f, it will cause the medium boundary, when it arrives there, to oscillate at that frequency. As a result of that, the wave that is set up in the second medium—which we call the transmitted wave—will also have the same frequency f. Again, think of the two strings tied together, so the first string “drives” the second one at the frequency f; or the sound at the air-water boundary, driving (pushing) the water surface at the frequency f. So, the incident and transmitted waves will have the same frequency, but it is clear that, if the wave speeds in the two media are different, they cannot have the same wavelength: since the relation (12.4) has to hold, we will have λ1 = c1/f, and λ2 = c2/f. Thus, if a periodic wave goes from a slower to a faster medium, its wavelength will increase, and if it goes from a faster to a slower one, the wavelength will decrease. It is easy to see physically why this happens, and how it has to be the case even for non-periodic 1This effect can be used to produce “funny voices,” because of the relationship f = c/λ (Eq. (12.4)), which will be discussed in greater detail in the section on standing waves.
University Physics I Classical Mechanics_Page_304_Chunk4502
12.1. TRAVELING WAVES 287 waves, that is, wave pulses: a pulse going into a faster medium will widen in length (stretch), whereas a pulse going into a slower medium will become narrower (squeezed). Imagine, for example, several people walking in line, separated by the same distance d, all at the same pace, until they reach a line beyond which they are supposed to start running. When the first person reaches the line, he starts running, but the second one is still walking, so by the time the second one reaches the line the first one has increased his distance from the second. The same thing will happen between the second and the third, and so on: the original “bunch” will become spread out. (If you watch car races, chances are you have seen this kind of thing happen already!) Besides setting up a transmitted wave, with the properties I have just discussed, the incident wave will almost always cause a reflected wave to start traveling in the first medium, moving backwards from the boundary. The reflected wave also has the same frequency as the incident one, and since it is traveling in the same medium, it will also have the same wavelength. A non-periodic pulse, when reflected, will therefore not be stretched or squeezed, but it will be “turned around” back-to-front, since the first part to reach the boundary also has to be the first to leave. See Figure 12.4 (the top part) for an example. c2 = 2c1 c2 = c1/2 Figure 12.4: Reflection and transmission of a pulse at the boundary where two strings of different densities are joined. (“Before” and “after” situations are shown for each case.) Top figure: the string on the right is less dense, so the pulse travels faster (the tension on both strings is supposed to be the same). The reflected pulse is upright but reversed left-to-right. Bottom figure: the string on the right is more dense, so the transmitted pulse travels more slowly. The reflected pulse is reversed left-to-right and flipped upside down. What is the physical reason for the reflected wave? Ultimately, it has to do with the energy
University Physics I Classical Mechanics_Page_305_Chunk4503
288 CHAPTER 12. WAVES IN ONE DIMENSION carried by the incident wave, and whether it is possible for the transmitted wave alone to handle the incoming energy flux or not. As we saw earlier (Eq. (12.8)), the energy per unit volume in a harmonic wave of angular frequency ω and amplitude ξ0 is E/V = 1 2ρ0ω2ξ2 0. If the wave is traveling at a speed c, then the energy flux (energy transported per unit time per unit area) is equal to (E/V )c, which is to say I = 1 2cρ0ω2ξ2 0 (12.14) This is often called the intensity of the wave. It can be written as I = 1 2Zω2ξ2 0, where I have defined the medium’s mechanical impedance (or simply the impedance) as Z = cρ0 (12.15) (for a string, the mass per unit length µ instead of the mass per unit volume ρ0 should be used). You can see that if the two media have the same impedance, then the energy flux in medium 2 will exactly match that in medium 1, provided the incident and transmitted waves have the same amplitudes. In that case, there will be no reflected wave: even if the two media have different densities and wave velocities, as long as they have the same impedance, the wave will be completely transmitted. On the other hand, if the media have different impedances, then it will in general be impossible to match the energy flux with only a transmitted wave, and reflection will occur. This is not immedi- ately obvious, since it looks like all you have to do, to compensate for the different impedances in Eq. (12.14), is to give the transmitted wave an amplitude that is different from that of the incident wave. But the point is precisely that, mathematically, you cannot do that without introducing a reflected wave. This is because the actual amplitude of the oscillation at the boundary has to be the same on both sides, since the two media are connected there, and oscillating together; so, if ξ0,inc is going to be different from ξ0,trans, you need to have another wave in medium 1, the reflected wave, to insure that ξ0,inc + ξ0,refl= ξ0,trans. Another way to see this is to dig in a little deeper into the physical meaning of the impedance. This is a worthwhile detour, because impedance in various forms recurs in a number of physics and engineering problems. For a sound wave in a solid, for instance, we can see from Eqs. (12.13) and (12.15) that Z = cρ0 = √Y ρ0; so a medium can have a large impedance either by being very stiff (large Y ) or very dense (large ρ0) or both; either way, one would have to work harder to set up a wave in such a medium than in one with a smaller impedance. On the other hand, once the wave is set up, all that work gets stored as energy of the wave, so a wave in a medium with larger Z will also carry a larger amount of energy (as is also clear from Eq. (12.14))2 for a given displacement ξ0. So, when a wave is trying to go from a low impedance to a large impedance medium, it will find 2In this respect, it may help you to think of the impedance of an extended medium as being somewhat analog to the inertia (mass) of a single particle. The larger the mass, the harder it is to accelerate a particle, but once you have given it a speed v, the larger mass also carries more energy.
University Physics I Classical Mechanics_Page_306_Chunk4504
12.2. STANDING WAVES AND RESONANCE 289 it hard to set up a transmitted wave: the transmitted wave amplitude will be small (compared to that of the incident wave), and the only way to satisfy the condition ξ0,inc + ξ0,refl= ξ0,trans will be to set up a reflected wave with a negative amplitude3—in effect, to flip the reflected wave upside down, in addition to left-to-right. This is the case illustrated in the bottom drawing in Figure 12.4. Conversely, you might think that a wave trying to go from a high impedance to a low impedance medium would have no trouble setting up a transmitted wave there, and that is true—but because of its low impedance, the transmitted wave will still not be able to carry all the energy flux by itself. In this case, ξ0,trans will be greater than ξ0,inc, and this will also call for a reflected wave in the first medium, only now it will be “upright,” that is, ξ0,refl= ξ0,trans −ξ0,inc > 0. To finish up the subject of impedance, note that the observation we just made, that impedance will typically go as the square root of the product of the medium’s “stiffness” times its density, is quite general. Hence, a medium’s density will typically be a good proxy for its impedance, at least as long as the “stiffness” factor is independent of the density (as for strings, where it is just equal to the tension) or, even better, increases with it (as is typically the case for sound waves in most materials). Thus, you will often hear that a reflected wave is inverted (flipped upside down) when it is reflected from a denser medium, without any reference to the impedance—it is just understood that “denser” also means “larger impedance” in this case. Also note, along these lines, that a “fixed end,” such as the end of a string that is tied down (or, for sound waves, the closed end of an organ pipe), is essentially equivalent to a medium with “infinite” impedance, in which case there is no transmitted wave at that end, and all the energy is reflected. Finally, the expression ξ0,inc + ξ0,reflthat I wrote earlier, for the amplitude of the wave in the first medium, implicitly assumes a very important property of waves, which is the phenomenon known as interference, or equivalently, the “linear superposition principle.” According to this principle, when two waves overlap in the same region of space, the total displacement is just equal to the algebraic sum of the displacements produced by each wave separately. Since the displacements are added with their signs, one may get destructive interference if the signs are different, or constructive interference if the signs are the same. This will play an important role in a moment, when we start the study of standing waves. 12.2 Standing waves and resonance Imagine you have a sinusoidal traveling wave of the form (12.5), only traveling to the left, incident from the right on a “fixed end” at x = 0. The incident wave will go as ξ0 sin[2π(x + ct)/λ]; the reflected wave should be flipped left to right and upside down, so change x to −x and put an overall 3A better way to put this would be to say that the amplitude is positive as always, but the reflected wave is 180◦ out of phase with the incident wave, so the amplitude of the total wave on the medium 1 side of the boundary is ξ0,inc −ξ0,refl.
University Physics I Classical Mechanics_Page_307_Chunk4505
290 CHAPTER 12. WAVES IN ONE DIMENSION minus sign on the displacement, to get −ξ0 sin[2π(−x + ct)/λ]. The sum of the two waves in the region x > 0 is then ξ(x, t) = ξ0 sin 22π λ (x + ct) 3 −ξ0 sin 22π λ (−x + ct) 3 = 2ξ0 sin $2πx λ % cos (2πft) (12.16) using a trigonometrical identity for sin(a + b), and f = c/λ. The result on the right-hand side of Eq. (12.16) is called a standing wave. It does not travel anywhere, it just oscillates “in place”: every point x behaves like a separate oscillator with an amplitude 2ξ0 sin(2πx/λ). This amplitude is zero at special points, where 2x/λ is equal to an integer. These points are called nodes. We could think of “confining” a wave of this sort to a string fixed at both ends, if we make the string have an end at x = 0 and the other one at one of these points where the amplitude is zero; this means we want the length L of the string to satisfy 2L = nλ (12.17) where n = 1, 2, . . .. Alternatively, we can think of L as being fixed and Eq. (12.17) as giving us the possible values of λ that will give us standing waves: λ = 2L/n. Since f = c/λ, we see that all these possible standing waves, for fixed L and c, have different frequencies that we can write as fn = nc 2L, n = 1, 2, 3, . . . (12.18) Note that these are all multiples of the frequency f1 = c/2L. We call this the fundamental frequency of oscillation of a string fixed at both ends. The period corresponding to this fundamental frequency is the roundtrip time of a wave pulse around the string, 2L/c. The first three standing waves are plotted in Figure 12.5 (next page). Their wave functions are given by the right-hand side of Eq. (12.16), for 0 ≤x ≤L, with λ = 2L/n (n = 1, 2, 3), and f = fn = nc/2L. The amplitude is arbitrary; in the figure I have set it equal to 1 for convenience. Calling the corresponding function un(x, t) is more or less common practice in other contexts: un(x, t) = sin &nπx L ' cos (2πfnt) (12.19) These functions are called the normal modes of vibration of the string. In Figure 12.5 I have shown, for each of them, the displacement at the initial time, t = 0, as a solid line, and then half a period later as a dashed line. In addition to this, notice that the wave function vanishes identically (the string is flat) at the quarter-period intervals, t = 1/4fn and t = 3/4fn. At those times, the wave has no elastic potential energy (since the string is unstretched): as with a simple oscillator passing through the equilibrium position, all its energy is kinetic. For n > 1, there are also nodes (places where the oscillation amplitude is always zero) at points other than the ends. Including the endpoints, the n-th normal mode has n + 1 nodes. The places where the oscillation amplitude is largest are called antinodes.
University Physics I Classical Mechanics_Page_308_Chunk4506
12.2. STANDING WAVES AND RESONANCE 291 -1 0 1 0 0.2 0.4 0.6 0.8 1 -1 0 1 -1 0 1 x/L ξ/ξ0 Figure 12.5: The three lowest-frequency normal modes of vibration of a string held down at both ends, corresponding to, from top to bottom, n = 1, 2, 3 Animations of these standing waves can be found in many places; one I particularly like is here: http://newt.phys.unsw.edu.au/jw/strings.html#standing. It also shows graphically how the standing wave can be considered as a superposition of two oppositely-directed traveling waves, as in Eq. (12.16). If we initially bent the string into one of the shapes shown in Fig. 12.5, and then released it, it would oscillate at the corresponding frequency fn, keeping the same shape, only scaling it up and down by a factor cos(2πfnt) as time elapsed. So, another way to think of standing waves is as the natural modes of vibration of an extended system—the string, in this case, although standing waves can be produced in any medium that can carry a traveling wave. What I mean by a “natural mode of vibration” is the following: a single oscillator, say, a pendulum, has a single “natural” frequency; if you displace it or hit it, it just oscillates at that frequency with a constant amplitude. An extended system, like the string, can be viewed as a collection of coupled oscillators, which may in general oscillate in many different and complicated ways; yet, there is a specific set of frequencies—for the string with two ends fixed, the sequence fn of Eq. (12.18)—and associated shapes that will result in all the parts of the string performing simple harmonic motion, in synchrony, all at the same frequency. Of course, to produce just one of these specific modes of oscillation requires some care (“driving” the string at the right frequency is probably the easiest way; see next paragraph); however, if you simply hit or pluck the string in any random way, a remarkable thing happens: the resulting motion will be, mathematically, described as a sum of sinusoidal standing waves, each with one
University Physics I Classical Mechanics_Page_309_Chunk4507
292 CHAPTER 12. WAVES IN ONE DIMENSION of the frequencies fn, and each with a different amplitude An. In a musical instrument, this will eventually generate a superposition of sound waves with frequencies f1 = c/2L, f2 = 2f1, f3 = 3f1 . . . (called, in this context, the fundamental, f1, and its overtones, fn = nf1). Each one of these frequencies corresponds to a different pitch, or musical note, and the result will sound a little like a chord, although not nearly as pronounced—we will mostly hear only the fundamental, which corresponds to the root note of the chord, but all the notes in a major triad are in fact present in the vibration of a single guitar or piano string4. But wait, there’s more! Suppose that you try to get the string to oscillate by “driving” it: that is to say, grabbing a hold of one end and shaking it at some frequency, only with a very small amplitude, so the displacement at that end remains always close to zero. In that case, you will typically get only very small amplitude oscillations, until the driving frequency hits one of the special frequencies fn, at which point you will get a large oscillation with the shape of the corresponding standing wave. This is a phenomenon known as resonance, and the fn are the resonant frequencies of this system. Note that the effect I just described is essentially the same as you experience when you are “pump- ing,” or simply pushing, a swing. Unless you do it at the right frequency, you do not get very far; but if you do it at the right frequency (which is the swing’s natural frequency, the one at which it will swing on its own), you can get huge amplitude oscillations. So, the frequencies (12.18) may be said to be the string’s natural oscillation frequencies in the same two ways: they are the ones at which it will oscillate if you just pluck it, and they are the ones at which you have to drive it if you want to get large oscillations. Pretty much everything I have just shown you above for standing waves on a string applies to sound waves inside a tube or pipe open at both ends. In that case, however, it is not the displacement, but the pressure (or density) wave that must have zeros at the ends (since the ends are open, the pressure there must be just the average atmospheric pressure; note that the pressure or density waves in a sound wave do not give the absolute pressure or density, but the deviation, positive or negative, from the average). The math, however, is identical, and one finds the same set of normal modes and resonance frequencies as above. These are then the frequencies that would be produced when blowing in a flute or an organ pipe open at both ends. So, both from pipes and strings we get the same “harmonic series” of frequencies (12.18) that has been the foundation of Western music since at least the time of Pythagoras. 4It works like this: say f1 corresponds to a C, then f2 is the C above that, f3 the G above that, f4 the C above that, and f5 the E above that.
University Physics I Classical Mechanics_Page_310_Chunk4508
12.3. CONCLUSION, AND FURTHER RESOURCES 293 12.3 Conclusion, and further resources This chapter on one-dimensional waves has barely scratched the surface of the extremely rich world of wave phenomena. I have only given you a passing glance at interference, and I have not said anything at all about diffraction, the Doppler effect, polarization, refraction. . .. Many of these things you will learn about in later courses, most likely when you encounter electromagnetic waves (which are non-mechanical, but described by the same mathematical equation). Waves are such an intrinsically kinetic phenomenon that they are best appreciated by watch- ing them in action, or, as a second-best alternative, through animations. A wonderful repos- itory of such movies and animations is PHYSCLIPS at the University of New South Wales: http://www.animations.physics.unsw.edu.au/waves-sound/oscillations/index.html They also have a set of pages on the “physics of music” that I have already mentioned a couple of times. If you are interested in this topic, you should go spend some time there! http://newt.phys.unsw.edu.au/music Finally, closer to home, the fellows at PhET (University of Colorado), have this great interactive app to explore waves on a string: https://phet.colorado.edu/en/simulation/wave-on-a-string 12.4 In summary 1. A traveling wave in an elastic medium is a collective disturbance of the particles in the medium (a displacement, or change in pressure or density) that carries energy and momentum from one point of the medium to another, over a distance that is typically much larger than the displacement of the individual particles making up the wave. 2. In a longitudinal wave, the displacement of the particles is along the line of motion of the wave; in a transverse wave, it is perpendicular to the wave’s motion. 3. An important kind of waves are periodic waves, in which the disturbance repeats itself at each point in the medium with a period T. Sinusoidal, periodic waves are called harmonic waves. Their spatial period is called the wavelength λ. If the speed of the wave is c, one has c = fλ, where f = 1/T is the wave frequency. 4. The time-averaged energy density in a harmonic wave (sum of kinetic and elastic potential energy per unit volume) is E/V = ρ0ω2ξ2 0/2, where ρ0 is the medium’s density, and ξ0 the amplitude of the displacement oscillations. The time average momentum density is E/cV . The intensity of the wave (energy carried per unit time per unit area) is cE/V .
University Physics I Classical Mechanics_Page_311_Chunk4509
294 CHAPTER 12. WAVES IN ONE DIMENSION 5. Sound is a longitudinal compression-and-rarefaction wave in an elastic medium. It can be described in terms of displacement, pressure or density. The pressure or density disturbance is maximal where the displacement is zero, and vice-versa. 6. The speed of sound in a solid with Young modulus Y is c = ! Y/ρ0; in a fluid with bulk modulus B, it is c = ! B/ρ0. In an ideal gas, this depends only on the ratio of specific heats, the molar mass, and the temperature. 7. Transverse waves on a string with mass per unit length µ and under a tension F t travel with a speed c = ! F t/µ. 8. When a wave reaches the boundary between two media, it is typically partly reflected and partly transmitted. The incident, reflected and transmitted waves all have the same frequency. The transmitted wave has a wavelength c2/f, where c2 is the wave speed in the second medium. 9. The quantity that determines how much of the energy is reflected or transmitted is the mechanical impedance, defined for each medium as Z = cρ0. If Z1 = Z2 there is no reflected wave. If Z1 < Z2, the reflected wave is inverted (flipped upside-down) relative to the incident wave. If Z1 > Z2, it is upright. 10. Standing waves arise in a medium that is confined to a region of space, and are the normal (or “natural”) modes of vibration of the system. In a standing wave, each particle of the medium oscillates with an amplitude that is a fixed function of the particle’s position (a sinusoidal function in one dimension). This amplitude is zero at points called nodes. 11. In one dimension, all the standing wave frequencies are multiples of a fundamental frequency f1 = c/2L, where L is the length of the medium (as long as the boundary conditions at both ends of the medium are identical). These are the resonant frequencies of the system: if disturbed, it will naturally oscillate in a superposition of these frequencies, and if driven at one of these frequencies, one will obtain a large response.
University Physics I Classical Mechanics_Page_312_Chunk4510
12.5. EXAMPLES 295 12.5 Examples 12.5.1 Displacement and density/pressure in a longitudinal wave The picture below shows the displacement of a medium (let’s say air) as a sound pulse travels through it. (Don’t worry about the units on the axes right now! We are only interested in qualitative results here.) ξ displacement direction of propagation of the wave (x) x (a) Sketch the corresponding pressure (or density) pulse. Note: pressure and density are in phase, so one is large where the other is large. In either case what is always plotted is the difference between the actual pressure or density and the average pressure (for air, atmospheric pressure) or density of the medium. (b) If this sound pulse is incident on water, sketch the reflected pulse, both in a displacement and in a pressure/density plot. Solution (a) The purpose of this example is to help refine the intuition you may have gotten from Figure 12.3 regarding the relationship between the displacement and the pressure/density in a longitudinal wave. When discussing Fig. 12.3, I argued that the density should be high at a point like x = π in that figure, because the particles to the left of that point were being pushed to the right, and those to the right were being pushed to the left. However, a similar argument can be made to show that the density should be higher than its equilibrium value whenever the displacement curve has a negative slope, in general. For instance, consider point x = 1 in the figure above. Particles both to the left and the right of that point are being pushed to the right (positive displacement), but the displacement is larger for the ones on the left, which will result in a bunching at x = 1.
University Physics I Classical Mechanics_Page_313_Chunk4511
296 CHAPTER 12. WAVES IN ONE DIMENSION Conversely, if you look at a point with positive slope, such as x = 0, you see that the particles on the right are pushed farther to the right than the particles on the left, which means the density around x = 0 will drop. From this you may conclude that the density versus position graph will look somewhat like the negative of the derivative of the ξ-vs.-x graph: positive when ξ falls, negative when it rises, and zero at the “turning points” (maxima or minima of ξ(x)). This is, in fact, mathematically true, and is illustrated in the figure below. density/pressure ξ displacement x x Figure 12.6: Illustrating the relationship between displacement (blue curve) and pressure/density (red) in a longitudinal wave. The dashed lines separate the regions where the pressure (or density) is positive (higher than in the absence of the wave) from those where it is negative. (b) If this sound wave is incident from air into water, it means it is going from a low impedance to a high impedance medium (both the density and the speed of sound are much greater in water than in air, giving a much larger Z = cρ0; see Eq. (12.15) for the definition of impedance). This means the reflected displacement pulse will be flipped upside down, as well as left to right (see the figure on the next page). This is just (except for the scale, which here is arbitrary) like the bottom part of Fig. 12.4.
University Physics I Classical Mechanics_Page_314_Chunk4512
12.5. EXAMPLES 297 However, if you now try to figure out the shape of the density/pressure wave based on the displace- ment wave, as we did in part (a), you’ll see that it is only reversed left to right, but not flipped upside down! This is a general property of longitudinal waves: the reflected pressure/density wave behaves in exactly the opposite way as the displacement wave, as far as the upside-down “flip” is concerned: it gets flipped when going from high impedance to low impedance, and not when going from low to high. density/pressure ξ displacement x x Figure 12.7: What the wave pulse in the previous figure would look like if reflected from a high-impedance medium. The displacement wave is reversed left to right and flipped upside down. The pressure/density wave is only reversed left to right. If you are curious to see how this happens mathematically, the idea is that the density wave is proportional to −dξ/dx, and the reflected displacement wave goes like ξrefl= −ξinc(−x), where the first minus sign gives the vertical flip and the second the horizontal one. Taking the derivative of this last expression with respect to x then removes the minus sign in front.
University Physics I Classical Mechanics_Page_315_Chunk4513
298 CHAPTER 12. WAVES IN ONE DIMENSION 12.5.2 Violin sounds The “sounding length” of a violin string, from the bridge to the nut at the upper end of the fingerboard, is about 32 cm. (a) If the string is tuned so that its fundamental frequency corresponds to a concert A (440 Hz), what is the speed of a wave on that string? (b) If the string’s density is 0.66 g/m (note: the “g” stands for “grams”!), what is the tension on the string? (c) When the string is played, its vibration is transmitted through the bridge to the violin plates. At what frequency will the plates vibrate? (d) The vibration of the plates then sets up a sound wave in air. What is the wavelength of this wave? Solution (a) In Section 12.2 we saw that the fundamental frequency of a string fixed at both ends is f1 = c/2L (corresponding to Eq. (12.18) with n = 1). Setting this equal to 440 Hz, and solving for c, c = 2Lf1 = 2 × (0.32 m) × 440 s−1 = 282 m s (b) From Section 12.1.3, we have that the speed of a wave on a string is c = ! F t/µ, where F t is the tension and µ the mass per unit length (Eq. (12.11). Solving for F t, F t = c2µ = & 282 m s '2 × 6.6 × 10−4 kg m = 52.5 N (c) The plates will vibrate at the same frequency as the string, 440 Hz, since they are driven by the motion of the string. (d) The basic relationship to use here is Eq. (12.4), f = c/λ, which we can solve for λ if we know c, the speed of sound in air. In Section 12.1.3 it was stated that the speed of sound in air is about 340 m/s, so we have λ = c f = 340 m/s 440 s−1 = 0.77 m
University Physics I Classical Mechanics_Page_316_Chunk4514
12.6. ADVANCED TOPICS 299 12.6 Advanced Topics 12.6.1 Chain of masses coupled with springs: dispersion, and long-wavelength limit. Consider a model of an extended elastic medium in which, for simplicity, we separate the two main medium properties, inertia and elasticity, by describing it as a chain of point-like masses (particles) connected by massless springs, as in Figure 12.8 below. I will show you here how one can get “ideal” wave behavior in this system, provided we work in the “long-wavelength” limit, that is to say, we consider only waves whose wavelength is much greater than the average distance between neighboring masses. ... ... ξn-1 ξn+1 ξn d Figure 12.8: A chain of masses connected by massless springs. The top picture shows the equilibrium posi- tions with the springs relaxed, the bottom one the situation where each mass has undergone a displacement ξ. In the figure above I have explicitly shown the n-th mass and the two springs that push and/or pull on it, both in equilibrium (top drawing) and when the chain is in motion (bottom). In the latter case, the length of the springs depends on the relative displacements of all three masses shown. Specifically, the length of the spring on the left is d+ξn −ξn−1, where d is the distance between the masses in equilibrium, and the length of the spring on the right is d + ξn+1 −ξn. If the left spring is stretched (length greater than d) it will pull to the left on the n-th mass, and, conversely, if the right spring is stretched (length greater than d) it will pull to the right on the n-th mass. So, if all the springs have the same constant k, the force equation F = ma for mass n is man = −k(ξn −ξn−1) + k(ξn+1 −ξn) (12.20) which we can rewrite as md2ξn dt2 = kξn−1 −2kξn + kξn+1 (12.21)
University Physics I Classical Mechanics_Page_317_Chunk4515
300 CHAPTER 12. WAVES IN ONE DIMENSION Now let us try to see if we can get a sinusoidal solution to this system of differential equations. By analogy with Eq. (12.3) let ξn(t) = A sin 4 2π &xn λ −ft '5 where xn = nd is the equilibrium position of the n-th mass. Then for each of the three masses considered, we have ξn−1(t) = A sin[2π((n −1)d/λ −ft)] = A sin[2π(nd/λ −ft) −2πd/λ] ξn(t) = A sin[2π(nd/λ −ft)] ξn+1(t) = A sin[2π((n + 1)d/λ −ft)] = A sin[2π(nd/λ −ft) + 2πd/λ] (12.22) We want to substitute all this in Eq. (12.21). We can use the trigonometric identity sin(a −b) + sin(a + b) = 2 sin a cos b to simplify ξn−1 + ξn+1: ξn−1 + ξn+1 = 2A sin 2 2π $nd λ −ft %3 cos $2πd λ % (12.23) then use 1 −cos x = 2 sin2(x/2) to yield kξn−1 −2kξn + kξn+1 = −4kA sin2 $πd λ % sin 2 2π $nd λ −ft %3 = −4k sin2 $πd λ % ξn (12.24) It is clear now that Eq. (12.21) will be satisfied provided the following condition holds: m(2πf)2 = 4k sin2 $πd λ % (12.25) Or, taking the square root and simplifying, f = 1 π * k m sin $πd λ % (12.26) This is clearly a more complicated relation between f and λ than just Eq. (12.4). However, since we can argue that Eq. (12.4) must always hold for a sinusoidal wave, what we have actually found is that the chain of masses and springs in Fig. (12.8) will support a sinusoidal wave provided the wave velocity depends on the wavelength as required by Eqs. (12.4) and (12.26): c = λf = * k m λ π sin $πd λ % (12.27) This is an instance of the phenomenon called dispersion: sinusoidal waves of different frequencies (or wavelengths) have different velocities. One thing that happens in the presence of dispersion is that, although a single (infinite), sinusoidal wave can travel without changing its shape (provided f and λ satisfy Eq. (12.26)), a general pulse will be distorted as it propagates through the medium, often severely so.
University Physics I Classical Mechanics_Page_318_Chunk4516
12.6. ADVANCED TOPICS 301 In the long wavelength limit, however, the dispersion in this model disappears. We can see this as follows. In that limit, λ ≫d (the wavelength is much greater than the distance between the masses), and therefore πd/λ ≪1; we can then make the small-angle approximation in Eq. (12.27), sin(πd/λ) ≃πd/λ, and end up with c ≃d * k m (12.28) This is of the general form ! stiffness/inertia (as per Eq. (12.10)). Basically, in the long-wavelength limit, the medium appears homogeneous to the wave—it cannot “tell” that it is a chain of discrete particles. When you consider that everything that looks homogeneous on a macroscopic scale is actually made of discrete atoms or molecules at the microscopic level, you can see that this model is perhaps not as artificial as it might seem, and that in general you should, in fact, expect some kind of dispersion to occur in any medium, at sufficiently small wavelengths.
University Physics I Classical Mechanics_Page_319_Chunk4517
302 CHAPTER 12. WAVES IN ONE DIMENSION 12.7 Problems Problem 1 When plucked, the D string on a guitar vibrates with a frequency of 147 Hz. (a) What would happen to this frequency if you were to increase the tension in the string? (b) The vibration of the string eventually produces a sound wave of the same frequency, traveling through the air. If the speed of sound in air is 340 m/s, what is the wavelength of this wave? Problem 2 Think of a flute as basically a cylindrical tube of length 0.6 m, open to the atmosphere at both ends. If the speed of sound in air is 340 m/s (a) What is the fundamental (lowest) frequency of a sound wave in a flute? (b) Is this a transverse or a longitudinal wave? (c) The speed of sound in helium is about 3 times that in air. How would the flute’s resonance frequencies change if you filled it with helium instead of air? Justify each of your answers briefly. Problem 3 The top picture shows a wave pulse on a string (string 1) traveling to the right, where the string is attached to another one (string 2, not shown). The bottom picture shows the reflected wave some time later. If the tension on both strings is the same, (a) Is string 2 more or less dense than string 1? (b) In which string will the wave travel faster? (c) Sketch what the reflected wave would look like if the strings’ densities were the opposite of what you answered in part (a). Explain each of your answers briefly.
University Physics I Classical Mechanics_Page_320_Chunk4518
Chapter 13 Thermodynamics 13.1 Introduction The last two lectures this semester are about thermodynamics, an extremely important branch of physics that developed throughout the 19th century, motivated in part by the development of the steam engines that brought about the Industrial Revolution. Physics majors will study ther- modynamics at much greater length in University Physics III and subsequent courses, whereas Engineering and Chemistry majors will encounter it also in specialized courses in their own disci- plines. There is really no escaping thermodynamics, but you may wonder why bring it up here (in this course, at this time) at all? The answer is twofold: • From the point of view of the study of energy and its transformations, which has been one of the major themes of this course, thermodynamics provides us with the last missing pieces: it is here that we find out what thermal energy really is, and how it is different from other forms of energy (so much so, that we say that energy has been “dissipated” or “lost” when it becomes thermal energy). It is also here that we deal with the other way that energy can be transferred from a system to another (other, that is, than by doing work): this is the “direct transfer of thermal energy,” or what is normally called an exchange of heat. • From the point of view of the study of motion, which has been also another running theme, thermodynamics also represents the next logical step beyond what we have learned so far. Recall that we started looking at the motion of extended objects as if they were simple point particles, moving as a whole along with their center of mass, and slowly introduced tools to deal with more complex kinds of motion: first rigid body rotations, then elastic deformations 303
University Physics I Classical Mechanics_Page_321_Chunk4519
304 CHAPTER 13. THERMODYNAMICS (waves) in which the constituent parts of an object move relative to each other in a way that looks “organized,” or synchronized, from a macroscopic perspective. What is needed next is to account for the random motion, on a microscopic scale, of the smallest parts (atoms or molecules) that make up an extended object. This motion is constantly happening, and it is a key ingredient of the concepts of thermal energy and temperature. Conceptually, thermodynamics involves the introduction of two new physical quantities, tempera- ture and entropy. Temperature will be introduced in this lecture, and entropy in the next one. It is interesting to note from the start, however, that these are very different from all the quantities we have introduced so far this semester, in a fundamental way. In classical physics, at least, there is no difficulty in extending all those other quantities to the study of the smallest parts making up an object: we can perfectly well talk about the position, velocity or energy of a molecule. But temperature and entropy are statistical quantities, which are only properly defined, from a funda- mental point of view, for a large collection of (small) subsystems: it makes no sense to speak about the temperature or the entropy of a single molecule. This shows that there was really a profound change in perspective and methodology in classical physics when statistical mechanics (the part of physics that provides a microscopic foundation for thermodynamics) was developed. 13.2 Introducing temperature 13.2.1 Temperature and heat capacity The change in perspective that I just mentioned also means that it is not easy to even define temperature, beyond our natural intuition of “hot” and “cold,” or the somewhat circular notion that temperature is simply “what thermometers measure.” Roughly speaking, though, temperature is a measure of the amount (or, to be somewhat more precise, the concentration) of thermal energy in an object. When we directly put an amount of thermal energy, ∆Eth (what we will be calling heat in a moment), in an object, we typically observe its temperature to increase in a way that is approximately proportional to ∆Eth, at least as long as ∆Eth is not too large: ∆T = ∆Eth C (13.1) The proportionality constant C is called the heat capacity of the object: according to Eq. (13.1), a system with a large heat capacity could absorb (or give off—the equation is supposed to apply in either case) a large amount of thermal energy without experiencing a large change in temperature. If the system does not do any work in the process (recall Eq. (7.20)!), then its internal energy will increase (or decrease) by exactly the same amount of thermal energy it has taken in (or given off)1, 1If the system does do some work (or has work done on it), then Eq. (13.8) applies; see below.
University Physics I Classical Mechanics_Page_322_Chunk4520
13.2. INTRODUCING TEMPERATURE 305 and we can use the heat capacity2 to, ultimately, relate the system’s temperature to its energy content in a one-to-one-way. What is found experimentally is that the heat capacity of a homogeneous object (that is, one made of just one substance) is, in general, proportional to its mass. This is why, instead of tables of heat capacities, what we compile are tables of specific heats, which are heat capacities per kilogram (or sometimes per mole, or per cubic centimeter. . . but all these things are ultimately proportional to the object’s mass). In terms of a specific heat c = C/m, and again assuming no work done or by the system, we can rewrite Eq. (13.1) to read ∆Esys = mc∆T (13.2) or, again, ∆T = ∆Esys mc (13.3) which shows what I said above, that temperature really measures, not the total energy content of an object, but its concentration—the thermal energy “per unit mass,” or, if you prefer (and somewhat more fundamentally) “per molecule.” An object can have a great deal of thermal energy just by virtue of being huge, and yet still be pretty cold (water in the ocean is a good example). In fact, we can also rewrite Eqs. (13.1–13.3) in the (somewhat contrived-looking) form C = mc = m∆Esys/m ∆T (13.4) which tells you that an object can have a large heat capacity in two ways: one is simply to have a lot of mass, and the other is to have a large specific heat. The first of these ways is kind of boring (but potentially useful, as I will discuss below); the second is interesting, because it means that a relatively large change in the internal energy per molecule (roughly speaking, the numerator of (13.4)) will only show as a relatively small change in temperature (the denominator of (13.4); a large numerator and a small denominator make for a large fraction!). Put differently, and somewhat fancifully, substances with a large specific heat are very good at hiding their thermal energy from thermometers (see Fig. 13.1 for an example). This, as I said, is an interesting observation, but it also means that measuring heat capacities—or, for that matter, measuring temperature itself—may not be an easy matter. How do we get at the object’s internal energy if not through its temperature? Where does one start? 2Which, it must be noted, may also be a function of the system’s temperature—another complication we will cheerfully ignore here.
University Physics I Classical Mechanics_Page_323_Chunk4521
306 CHAPTER 13. THERMODYNAMICS Figure 13.1: In this simple model of a gas of diatomic molecules, each molecule can store “vibrational” potential energy (both potential and kinetic, through the oscillations of the “spring” that models the inter- action between the atoms), plus as at least two kinds of rotational kinetic energy (corresponding to rotations around the axes shown), in addition to just the translational kinetic energy of its center of mass. The latter is the only one directly measured by a gas thermometer, so a diatomic gas has many more ways of “hiding” its thermal energy (and hence, a larger specific heat) than a monoatomic gas. 13.2.2 The gas thermometer A good start, at least conceptually, is provided by looking at a system that has no place to hide its thermal energy—it has to show it all, have it, as it were, in full view all the time. Such a system is what has come to be known as an ideal gas—which we model, microscopically, as a collection of molecules (or, more properly, atoms) with no dimension and no structure: just pointlike things whizzing about and continually banging into each other and against the walls of their container. For such a system the only possible kind of internal energy is the sum of the molecules’ translational kinetic energy. We may expect this to be easily detected by a thermometer (or any other energy- sensitive probe), because as the gas molecules bang against the thermometer, they will indirectly reveal the energy they carry, both by how often and how hard they collide. As it turns out, we can be a lot more precise than that. We can analyze the theoretical model of an ideal gas that we have just described fairly easily, using nothing but the concepts we have introduced earlier in the semester (plus a few simple statistical ideas) and obtain the following result for the gas’ pressure and volume: PV = 2 3N⟨Ktrans⟩ (13.5) where N is the total number of molecules, and ⟨Ktrans⟩is the average translational kinetic energy per molecule. Now, you are very likely to have seen, in high-school chemistry, the experimentally derived “ideal gas law,” PV = nRT (13.6) where n is the number of moles, and R the “ideal gas constant.” Comparing Eq. (13.5) (a theoretical prediction for a mathematical model) and Eq. (13.6) (an empirical result approximately valid for
University Physics I Classical Mechanics_Page_324_Chunk4522
13.2. INTRODUCING TEMPERATURE 307 many real-world gases under a wide range of pressure and temperature, where “temperature” literally means simply “what any good thermometer would measure”) immediately tells us what temperature is, at least for this extremely simple system: it is just a measure of the average (translational) kinetic energy per molecule. It would be tempting to leave it at that, and immediately generalize the result to all kinds of other systems. After all, presumably, a thermometer inserted in a liquid is fundamentally responding to the same thing as a thermometer inserted in an ideal gas: namely, to how often, and how hard, the liquid’s molecules bang against the thermometer’s wall. So we can assume that, in fact, it must be measuring the same thing in both cases—and that would be the average translational kinetic energy per molecule. Indeed, there is a result in classical statistical mechanics that states that for any system (liquid, solid, or gas) in “thermal equilibrium” (a state that I will define more precisely later), the average translational kinetic energy per molecule must be ⟨Ktrans⟩= 3 2kBT (13.7) where kB is a constant called Boltzmann’s constant (kB = 1.38×10−23 J/K), and T, as in Eq. (13.6) is measured in degrees Kelvin. There is nothing wrong with this way to think about temperature, except that it is too self- limiting. To simply identify temperature with the translational kinetic energy per molecule leaves out a lot of other possible kinds of energy that a complex system might have (a sufficiently complex molecule may also rotate and vibrate, for instance, as shown in Fig. 13.1; these are some of the ways the molecule can “hide” its energy from the thermometer, as I suggested above). Typically, all those other forms of internal energy also go up as the temperature increases, so it would be at least a bit misleading to think of the temperature as having to do with only Ktrans, Eq. (13.7) notwithstanding. Ultimately, in fact, it is the total internal energy of the system that we want to relate to the temperature, which means having to deal with those pesky specific heats I introduced in the previous section. (As an aside, the calculation of specific heats was one of the great challenges to the theoretical physicists of the late 19th and early 20th century, and eventually led to the introduction of quantum mechanics—but that is another story!) In any case, the ideal gas not only provides us with an insight into the microscopic picture behind the concept of temperature, it may also serve as a thermometer itself. Equation (13.6) shows that the volume of an ideal gas held at constant pressure will increase in a way that’s directly proportional to the temperature. This is just how a conventional, old-fashioned mercury thermometer worked—as the temperature rose, the volume of the liquid in the tube went up. The ideal gas thermometer is a bit more cumbersome (a relatively small temperature change may cause a pretty large change in volume), but, as I stated earlier, typically works well over a very large temperature range. By using an ideal (or nearly ideal) gas as a thermometer, based on Eq. (13.6), we are, in fact, implicitly defining a specific temperature scale, the Kelvin scale (indeed, you may recall that for
University Physics I Classical Mechanics_Page_325_Chunk4523
308 CHAPTER 13. THERMODYNAMICS Eq. (13.6) to work, the temperature must be measured in degrees Kelvin). The zero point of that scale (what we call absolute zero) is the theoretical point at which an ideal gas would shrink to precisely zero volume. Of course, no gas stays ideal (or even gaseous!) at such low temperatures, but the point can easily be found by extrapolation: for instance, imagine plotting experimental values of V vs T, at constant pressure, for a nearly ideal gas, using any kind of thermometer scale to measure T, over a wide range of temperatures. Then, connect the points by a straight line, and extend the line to where it crosses the T axis (so V = 0); that point gives you the value of absolute zero in the scale you were using, such as −273.15 Celsius, for instance, or −459.67 Fahrenheit. V T (any scale) T = 0 (Kelvin scale) Figure 13.2: Illustrating how a gas thermometer can be used to define the Kelvin, or absolute, temperature scale. The connection between Kelvin (or absolute) temperature and microscopic motion expressed by equations like (13.5) through (13.7) immediately tells us that as you lower the temperature the atoms in your system will move more and more slowly, until, when you reach absolute zero, all microscopic motion would cease. This does not quite happen, because of quantum mechanics, and we also believe that it is impossible to really reach absolute zero for other reasons, but it is true to a very good approximation, and experimentalists have recently become very good at cooling small ensembles of atoms to temperatures extremely close to absolute zero, where the atoms move, literally, slower than snails (instead of whizzing by at close to the speed of sound, as the air molecules do at room temperature). 13.2.3 The zero-th law Historically, thermometers became useful because they gave us a way to quantify our natural perception of cold and hot, but the quantity they measure, temperature, would have been pretty useless if it had not exhibited an important property, which we naturally take for granted, but which is, in fact, surprisingly not trivial. This property, which often goes by the name of the zero-th law of thermodynamics, can be stated as follows: Suppose you place two systems A and B in contact, so they can directly exchange thermal energy (more about this in the next section), while isolating them from the rest of the world (so their joint
University Physics I Classical Mechanics_Page_326_Chunk4524
13.3. HEAT AND THE FIRST LAW 309 thermal energy has no other place to go). Then, eventually, they will reach a state, called thermal equilibrium, in which they will both have the same temperature. This is important for many reasons, not the least of which being that that is what allows us to mea- sure temperature with a thermometer in the first place: the thermometer tells us the temperature of the object with which we place it in contact, by first adopting itself that temperature! Of course, a good thermometer has to be designed so that it will do that while changing the temperature of the system being measured as little as possible; that is to say, the thermometer has to have a much smaller heat capacity than the system it is measuring, so that it only needs to give or take a very small amount of thermal energy in order to match its temperature. But the main point here is that the match actually happens, and when it does, the temperature measured by the thermometer will be the same for any other systems that are, in turn, in thermal equilibrium with—that is, at the same temperature as—the first one. The zero-th law only assures us that thermal equilibrium will eventually happen, that is, the two systems will eventually reach one and the same temperature; it does not tell us how long this may take, nor even, by itself, what that final temperature will be. The latter point, however, can be easily determined if you make use of conservation of energy (the first law, coming up!) and the concept of heat capacity introduced above (think about it for a minute). Still, as I said above, this result is far from trivial. Just imagine, for instance, two different ideal gases, whose molecules have different masses, that you bring to a state of joint thermal equilibrium. Equations (13.5) through (13.7) tell us that in this final state the average translational kinetic energy of the “A” molecules and the “B” molecules will be the same. This means, in particular, that the more massive molecules will end up moving more slowly, on average, so mav2 a,av = mbv2 b,av. But why is that? Why should it be the kinetic energies that end up matching, on average, and not, say, the momenta, or the molecular speeds themselves? The result, though undoubtedly true, defied a rigorous mathematical proof for decades, if not centuries; I am not sure that a rigorous proof exists, even now. 13.3 Heat and the first law 13.3.1 “Direct exchange of thermal energy” and early theories of heat In the previous section I have considered the possibility of “direct exchange of thermal energy” between two objects. This is a phenomenon with which we are all familiar: when a colder object is placed in contact with a warmer one, the warmer one cools offand the colder one warms up. This “warmth” that seems to flow out of one object and into the other is conventionally called “heat.”
University Physics I Classical Mechanics_Page_327_Chunk4525
310 CHAPTER 13. THERMODYNAMICS Naturally, this observation was made long before the concept of “energy” was even developed, and so heat was thought of, for a time, as an “invisible fluid” (called, at one point, “caloric fluid”), a sort of indestructible “substance” that literally passed from one body to another. By “indestructible” I mean that they had a notion of this caloric fluid being conserved: it was not created or destroyed, only exchanged from one body to another. This makes sense, in a way: if it was really something material, how could it be created or destroyed? Conservation of matter was pretty much accepted scientific “dogma” already by the end of the 18th century. This idea of conservation of the caloric fluid led to the whole field of “calorimetry,” as essentially a way to try to quantify (that is, measure) the amount of “caloric” that materials would take in or give off. The connection with temperature led directly to the definition of heat capacities and specific heats, just as I have introduced them above (in section 2.1); only instead of “change in energy” you would use “change in caloric content.” This would be measured in units, called calories, defined by the amount of caloric that led to a given temperature change in a reference substance, such as water. To be precise, let 1 calorie be the amount of “caloric” needed to raise the temperature of one gram of water by one degree Celsius at a pressure of one atmosphere. This makes the specific heat of water, by definition, 1 calorie/◦C·gram. Now imagine you place a hot object in a container of water, insulated from the rest of the world, and wait until thermal equilibrium is reached. Then you can calculate the “amount of caloric that flowed into the water,” from the change in its temperature, and if you assume that all this came from the hot object then you can calculate its heat capacity (in calories/◦C) from the change in its temperature. By proceeding in this fashion, scientists developed tables of specific heats that do not need any change today—only the recognition that “caloric” is not really a fluid at all, but a form of energy, and can, therefore, be measured in energy units. Clearly, conservation of caloric was a very good idea in its own way, since much of what was established back then still works if you simply replace the word “caloric” or “heat” by “thermal energy.” It was, however, ultimately unsatisfactory precisely because it restricted itself to what we would today recognize as just one kind of energy, and so it failed to recognize thermal energy as something that could be converted into, or from, other kinds of energy. In hindsight, it is a bit surprising that the belief in the conservation of caloric could have held for so long. What today appear to us like obvious instances of the transformation of (macroscopic) mechanical energy into thermal energy, such as the warmth generated when you rub two objects together, were explained away as instances of mechanically “squeezing” caloric fluid out of the objects. Around the turn of the 19th century, an American expatriate, Count Rumford, observed one of the most egregious instances of this in the enormous amount of “heat” that was generated in the boring of cannons (which involved, basically, a huge metal tool drilling a hole in a large metal cylinder). He noticed that the total mass of the metal, including all the shavings, did not appear to change in the process, and concluded that caloric had to be virtually massless, since enormous quantities of it could be “squeezed” out without an appreciable mass loss. He speculated that
University Physics I Classical Mechanics_Page_328_Chunk4526
13.3. HEAT AND THE FIRST LAW 311 caloric was not a fluid at all, but rather “a form of motion,” since only something like that could be made to increase without any apparent limit. Rumford’s theory was not generally accepted at the time, but later in the 19th century the direct conversion of mechanical energy into thermal energy was established beyond a doubt by James Prescott Joule in a series of painstaking experiments in which he used a system of weights to turn some vanes, or paddles, that stirred water in a container and eventually caused its temperature to rise. By measuring the mechanical energy deficit (gravitational plus kinetic) of his system of weights and paddles, he could tell how much energy the water must have gained, and by measuring the water’s change in temperature he could then establish the equivalent “amount of caloric” that had gone into it. He thus established what was called “the mechanical equivalent of heat,” which we would express today by saying that a calorie does not measure the amount of some (nonexistent) caloric fluid, but simply an amount of energy equal to 4.18 joules (and yes, the Joule is named after him!). 13.3.2 The first law of thermodynamics The upshot of all this experimentation was the full development of the concept of energy as a conserved quantity that manifested itself in different ways and could be “converted” among different kinds. To the observation, already familiar from macroscopic mechanics, that the energy of a system could be changed by doing work on it (or letting it do work on its environment) was added the observation, coming from thermal physics, that thermal energy could also be directly exchanged between two objects merely by placing them in contact, without any macroscopic work being involved. The two things taken together led to the principle of conservation of energy in its most general (pre-relativistic) form: ∆E = W + Q (13.8) which says simply that a change in the total energy of a system may result from work (W) or from “heat exchange” (Q). “Heat,” in physics usage today, is simply what we call the thermal energy that is directly transferred from one object to another, typically by contact; the convention used for this term is the same as for the work term, that is, Q is positive if thermal energy flows into the system and negative if thermal energy leaves the system. Equation (13.8) is the first law of thermodynamics. Note that, in terms of Q, the precise definition of a system’s heat capacity is C = Q/∆T, and so this will only be equal to ∆E/∆t when the system does no work, which is why I was careful to include that condition in the derivation of Eq. (13.2).
University Physics I Classical Mechanics_Page_329_Chunk4527
312 CHAPTER 13. THERMODYNAMICS 13.4 The second law and entropy The second law of thermodynamics is really little more than a formal statement of the observation that heat always flows spontaneously from a warmer to a colder object, and never in reverse. More precisely, consider two systems, at different temperatures, that can exchange heat with each other but are otherwise isolated from the rest of the world. The second law states that under those conditions the heat will only flow from the warmer to the colder one. The closure of the system—its isolation from any sources of energy—is important in the above statement. It is certainly possible to build devices that will remove heat from a relatively cold place (like the inside of your house on a hot summer day) and exhaust it to a warmer environment. These devices are called refrigerators or heat pumps, and the main thing about them is that they need to be plugged in to operate: that is, they require an external energy source. If you have an energy source, then, you can move heat from a colder to a warmer object. To avoid unnecessary complications and loopholes (what if the energy source is a battery that is physically inside your “closed” system?) an alternative formulation of the basic principle, due to Clausius, goes as follows: No process is possible whose sole result is the transfer of heat from a cooler to a hotter body The words “sole result” are meant to imply that in order to accomplish this “unnatural” transfer of heat you must draw energy from some source, and so you must be, in some way, depleting that source (the battery, for instance). On the other hand, for the reverse, “spontaneous” process—the flow from hotter to cooler—no such energy source is necessary. A mathematical way to formulate the second law would be as follows. Consider two systems, in thermal equilibrium at temperatures T1 and T2, that you place in contact so they can exchange heat. For simplicity, assume that exchange of heat is all that happens; no work is done either by the systems or on them, and no heat is transferred to or from the outside world either. Then, if Q1 and Q2 are the amounts of heat gained by each system, we must have, by the conservation of energy, Q2 = −Q1, so one of these is positive and the other one is negative, and, by the second law, the system with the positive Q (the one that gains thermal energy) must be the colder one. This is ensured by the following inequality: Q1(T2 −T1) ≥0 (13.9) So, if T2 > T1, Q1 must be positive, and if T1 > T2, Q1 must be negative. (The equal sign is there to allow for the case in which T1 = T2, in which case the two systems are initially in thermal equilibrium already, and no heat transfer takes place.)
University Physics I Classical Mechanics_Page_330_Chunk4528
13.4. THE SECOND LAW AND ENTROPY 313 Equation (13.9) is valid regardless of the temperature scale. If we use the Kelvin scale, in which all the temperatures are positive3, we can rewrite it by dividing both sides by the product T1T2, and using Q2 = −Q1, as Q1 T1 + Q2 T2 ≥0 (13.10) This more symmetric statement of the second law is a good starting point from which to introduce the concept of entropy, which I will proceed to do next. 13.4.1 Entropy In Equations (13.9) and (13.10), we have taken T1 and T2 to be the initial temperatures of the two systems, but in general, of course, these temperatures will change during the heat transfer process. It is useful to consider an “infinitesimal” heat transfer, dQ, so small that it leads to a negligible temperature change, and then define the change in the system’s entropy by dS = dQ T (13.11) Here, S denotes a new system variable, the entropy, which is implicitly defined by Eq. (13.11). That is to say, suppose you take a system from one initial state to another by adding or removing a series of infinitesimal amounts of heat. We take the change in entropy over the whole process to be ∆S = Sf −Si = " f i dQ T (13.12) Starting from an arbitrary state, we could use this to find the entropy for any other state, at least up to a (probably) unimportant constant (a little like what happens with the energy: the absolute value of the energy does not typically matter, it is only the energy differences that are meaningful). This may be easier said than done, though; there is no a priori guarantee that any two arbitrary states of a system could be connected by a process for which (13.12) could be calculated, and conversely, it might also happen that two states could be connected by several possible processes, and the integral in (13.12) would have different values for all those. In other words, there is no guarantee that the entropy thus defined will be a true state function—something that is uniquely determined by the other variables that characterize a system’s state in thermal equilibrium. Nevertheless, it turns out that it is possible to show that the integral (13.12) is indeed independent of the “path” connecting the initial and final states, at least as long as the physical processes considered are “reversible” (a constraint that basically amounts to the requirement that heat be exchanged, and work done, only in small increments at a time, so that the system never departs 3For a while in the 1970’s some people were very excited by the concept of negative absolute temperatures, but that is mostly an artificial contrivance used to describe systems that are not really in thermal equilibrium anyway.
University Physics I Classical Mechanics_Page_331_Chunk4529
314 CHAPTER 13. THERMODYNAMICS too far from a state of thermal equilibrium). I will not attempt the proof here, but merely note that this provides the following, alternative formulation of the second law of thermodynamics: For every system in thermal equilibrium, there is a state function, the entropy, with the property that it can never decrease for a closed system. You can see how this covers the case considered in the previous section, of two objects, 1 and 2, in thermal contact with each other but isolated from the rest of the world. If object 1 absorbs some heat dQ1 while at temperature T1 its change in entropy will be dS1 = dQ1/T1, and similarly for object 2. The total change in the entropy of the closed system formed by the two objects will then be dStotal = dS1 + dS2 = dQ1 T1 + dQ2 T2 (13.13) and the requirement that this cannot be negative (that is, Stotal must not decrease) is just the same as Eq. (13.10), in differential form. Once again, this simply means that the hotter object gives offthe heat and the colder one absorbs it, but when you look at it in terms of entropy it is a bit more interesting than that. You can see that the entropy of the hotter object decreases (negative dQ), and that of the colder one increases (positive dQ), but by a different amount: in fact, it increases so much that it makes the total change in entropy for the system positive. This shows that entropy is rather different from energy (which is simply conserved in the process). You can always make it increase just by letting a process “take its normal course”—in this case, just letting the heat flow from the warmer to the colder object until they reach thermal equilibrium with each other (at which point, of course, the entropy will stop increasing, since it is a function of the state and the state will no longer change). Although not immediately obvious from the above, the absolute (or Kelvin) temperature scale plays an essential role in the definition of the entropy, in the sense that only in such a scale (or another scale linearly proportional to it) is the entropy, as defined by Eq. (13.12), a state variable; that is, only when using such a temperature scale is the integral (13.12) path-independent. The proof of this (which is much too complicated to even sketch here) relies essentially on the Carnot principle, to be discussed next. 13.4.2 The efficiency of heat engines By the beginning of the 19th century, an industrial revolution was underway in England, due primarily to the improvements in the efficiency of steam engines that had taken place a few decades earlier. It was natural to ask how much this efficiency could ultimately be increased, and in 1824, a French engineer, Nicolas Sadi Carnot, wrote a monograph that provided an answer to this question.
University Physics I Classical Mechanics_Page_332_Chunk4530
13.4. THE SECOND LAW AND ENTROPY 315 Carnot modeled a “heat engine” as an abstract machine that worked in a cycle. In the course of each cycle, the engine would take in an amount of heat Qh from a “hot reservoir,” give off(or “exhaust”) an amount of heat |Qc| to a “cold reservoir,” and produce an amount of work |W|. (I am using absolute value bars here because, from the point of view of the engine, Qc and W must be negative quantities.) At the end of the cycle, the engine should be back to its initial state, so ∆Eengine = 0. The hot and cold reservoirs were supposed to be systems with very large heat capacities, so that the change in their temperatures as they took in or gave offthe heat from or to the engine would be negligible. If ∆Eengine = 0, we must have ∆Eengine = Qh + Qc + W = Qh −|Qc| −|W| = 0 (13.14) that is, the work produced by the engine must be |W| = Qh −|Qc| (13.15) The energy input to the engine is Qh, so it is natural to define the efficiency as ϵ = |W|/Qh; that is to say, the Joules of work done per Joule of heat taken in. A value of ϵ = 1 would mean an efficiency of 100%, that is, the complete conversion of thermal energy into macroscopic work. By Eq. (13.15), we have ϵ = |W| Qh = Qh −|Qc| Qh = 1 −|Qc| Qh (13.16) which shows that ϵ will always be less than 1 as long as the heat exhausted to the cold reservoir, Qc, is nonzero. This is always necessarily the case for steam engines: the steam needs to be cooled offat the end of the cycle, so a new cycle can start again. Carnot considered a hypothetical “reversible” engine (sometimes called a Carnot machine), which could be run backwards, while interacting with the same two reservoirs. In backwards mode, the machine would work as a refrigerator or heat pump. It would take in an amount of work W per cycle (from some external source) and use that to absorb the amount of heat |Qc| from the cold reservoir and dump the amount Qh to the hot reservoir. Carnot argued that no heat engine could have a greater efficiency than a reversible one working between the same heat reservoirs, and, consequently, that all reversible engines, regardless of their composition, would have the same efficiency when working in between the same temperatures. His argument was based on the observation that a hypothetical engine with a greater efficiency than the reversible one could be used to drive a reversible one in refrigerator mode, to produce as the sole result the transfer of some net amount of heat from the cold to the hot reservoir4, something that we argued in Section 1 should be impossible. 4The greater efficiency engine could produce the same amount of work as the reversible one while absorbing less heat from the hot reservoir and dumping less heat to the cold one. If all the work output of this engine were used to drive the reversible one in refrigerator mode, the result would be, therefore, a net flow of heat out of the cold one and a net flow of heat into the hot one.
University Physics I Classical Mechanics_Page_333_Chunk4531
316 CHAPTER 13. THERMODYNAMICS What makes this result more than a theoretical curiosity is the fact that an ideal gas would, in fact, provide a suitable working substance for a Carnot machine, if put through the following cycle (the so-called “Carnot cycle”): an isothermal expansion, followed by an adiabatic expansion, then an isothermal compression, and finally an adiabatic compression. What makes this ideally reversible is the fact that the heat is exchanged with each reservoir only when the gas is at (nearly) the same temperature as the reservoir itself, so by just “nudging” the temperature up or down a little bit you can get the exchange to go either way. When the ideal gas laws are used to calculate the efficiency of such a machine, the result (the Carnot efficiency) is ϵC = 1 −Tc Th (13.17) where the temperatures must be measured in degrees Kelvin, the natural temperature scale for an ideal gas. It is actually easy to see the connection between this result and the entropic formulation of the second law presented above. Suppose for a moment that Carnot’s principle does not hold, that is to say, that we can build an engine with ϵ > ϵC = 1 −Tc/Th. Since (13.16) must hold in any case (because of conservation of energy), we find that this would imply 1 −|Qc| Qh > 1 −Tc Th (13.18) and then some very simple algebra shows that −Qh Th + |Qc| Tc < 0 (13.19) But now consider the total entropy of the system formed by the engine and the two reservoirs. The engine’s entropy does not change (because it works in a cycle); the entropy of the hot reservoir goes down by an amount −Qh/Th; and the entropy of the cold reservoir goes up by an amount |Qc|/Tc. So the left-hand side of Eq. (13.19) actually equals the total change in entropy, and Eq. (13.19) is telling us that this change is negative (the total entropy goes down) during the operation of this hypothetical heat engine whose efficiency is greater than the Carnot limit (13.17). Since this is impossible (the total entropy of a closed system can never decrease), we conclude that the Carnot limit must always hold. As you can see, the seemingly trivial observation with which I started this section (namely, that heat always flows spontaneously from a hotter object to a colder object, and never in reverse) turns out to have profound consequences. In particular, it means that the complete conversion of thermal energy into macroscopic work is essentially impossible5, which is why we treat mechanical energy as “lost” once it is converted to thermal energy. By Carnot’s theorem, to convert some of that 5At least it is impossible to do using a device that runs in a cycle. For a one-use-only, you might do something like pump heat into a gas and allow it to expand, doing work as it does so, but eventually you will run out of room to do your expanding into. . .
University Physics I Classical Mechanics_Page_334_Chunk4532
13.4. THE SECOND LAW AND ENTROPY 317 thermal energy back to work we would need to introduce a colder reservoir (and take advantage, so to speak, of the natural flow of heat from hotter to colder), and then we would only get a relatively small conversion efficiency, unless the cold reservoir is really at a very low Kelvin temperature (and to create such a cold reservoir would typically require refrigeration, which again consumes energy). It is easy to see that Carnot efficiencies for reservoirs close to room temperature are rather pitiful. For instance, if Th = 300 K and Tc = 273 K, the best conversion efficiency you could get would be 0.09, or 9%. 13.4.3 But what IS entropy, anyway? The existence of this quantity, the entropy, which can be measured or computed (up to an arbitrary reference constant) for any system in thermal equilibrium, is one of the great discoveries of 19th century physics. There are tables of entropies that can be put to many uses (for instance, in chemistry, to figure out which reactions will happen spontaneously and which ones will not), and one could certainly take the point of view that those tables, plus the basic insight that the total entropy can never decrease for a closed system, are all one needs to know about it. From this perspective, entropy is just a convenient number that we can assign to any equilibrium state of any system, which gives us some idea of which way it is likely to go if the equilibrium is perturbed. Nonetheless, it is natural for a physicist to ask to what, exactly, does this number correspond? What property of the equilibrium state is actually captured by this quantity? Especially, in the context of a microscopic description, since that is, by and large, how physicists have always been trying to explain things, by breaking them up into little pieces, and figuring out what the pieces were doing. What are the molecules or atoms of a system doing in a state of high entropy that is different from a state of low entropy? The answer to this question is provided by the branch of physics known as Statistical Mechanics, which today is mostly quantum-based (since you need quantum mechanics to describe most of what atoms or molecules do, anyway), but which started in the context of pure classical mechanics in the mid-to-late 1800’s and, despite this handicap, was actually able to make surprising headway for a while. From this microscopic, but still classical, perspective (which applies, for instance, moderately well to an ideal gas), the entropy can be seen as a measure of the spread in the velocities and positions of the molecules that make up the system. If you think of a probability distribution, it has a mean value and a standard deviation. In statistical mechanics, the molecules making up the system are described statistically, by giving the probability that they might have a certain velocity or be at some point or another. These probability distributions may be very narrow (small standard deviation), if you are pretty certain of the positions or the velocities, or very broad, if you are not very certain at all, or rather expect the actual velocities and positions to be spread over a
University Physics I Classical Mechanics_Page_335_Chunk4533
318 CHAPTER 13. THERMODYNAMICS considerable range of values. A state of large entropy corresponds to a broad distribution, and a state of small entropy to a narrow one. For an ideal gas, the temperature determines both the average molecular speed and the spread of the velocity distribution. This is because the average velocity is zero (since it is just as likely to be positive or negative), so the only way to make the average speed (or root-mean-square speed) large is to have a broad velocity distribution, which makes large speeds comparatively more likely. Then, as the temperature increases, so does the range of velocities available to the molecules, and correspondingly the entropy. Similarly (but more simply), for a given temperature, a gas that occupies a smaller volume will have a smaller entropy, since the range of positions available to the molecules will be smaller. These considerations may help us understand an important property of entropy, which is that it increases in all irreversible processes. To begin with, note that this makes sense, since, by definition, these are processes that do not “reverse” spontaneously. If a process involves an increase in the total entropy of a closed system, then the reverse process will not happen, because it would require a spontaneous decrease in entropy, which the second law forbids. But, moreover, we can see the increase in entropy directly in many of the irreversible processes we have considered this semester, such as the ones involving friction. As I just pointed out above, in general, we may expect that increasing the temperature of an object will increase its entropy (other things being equal), regardless of how the increase in temperature comes about. Now, when mechanical energy is lost due to friction, the temperature of both of the objects (surfaces) involved increases, so the total entropy will increase as well. That marks the process as irreversible. Another example of an irreversible process might be the mixing of two gases (or of two liquids, like cream and coffee). Start with all the “brown” molecules to the left of a partition, and all the “white” molecules to the right. After you remove the partition, the system will reach an equilibrium state in which the range of positions available to both the brown and white molecules has increased substantially—and this is, according to our microscopic picture, a state of higher entropy (other things, such as the average molecular speeds, being equal6). For quantum mechanical systems, where the position and velocity are not simultaneously well defined variables, one uses the more abstract concept of “state” to describe what each molecule is doing. The entropy of a system in thermal equilibrium is then defined as a measure of the total number of states available to its microscopic components, compatible with the constraints that determine the macroscopic state (such as, again, total energy, number of particles, and volume). 6In the case of cream and coffee, the average molecular speeds will not be equal—the cream will be cold and the coffee hot—but the resulting exchange of heat is just the kind of process I described at the beginning of the chapter, and we have seen that it, too, results in an increase in the total entropy.
University Physics I Classical Mechanics_Page_336_Chunk4534
13.5. IN SUMMARY 319 13.5 In summary 1. Temperature is a statistical quantity that provides a (typically indirect) measure of the con- centration of thermal energy in a system. For a system that is (approximately) well described by classical mechanics, the temperature, as measured by a conventional thermometer, is di- rectly proportional to the average translational kinetic energy per molecule. 2. In a process in which a system does no work, a change in the system’s temperature is related to a change in its total internal energy (which typically includes more than just translational kinetic energy contributions) by ∆E = C∆T, where C is the system’s heat capacity for the process. 3. The transfer of thermal energy between two systems without either one doing macroscopic work on each other is generally possible. Thermal energy transferred in this way is called heat, and denoted by the symbol Q. 4. The actual definition of a system’s heat capacity is C = Q/∆T. For a homogeneous system (made of just one substance), C = mc, where m is the system’s mass and c the substance’s specific heat. Specific heats typically depend on temperature in nontrivial ways. 5. Two systems isolated from the rest of the world but allowed to exchange thermal energy with each other will eventually reach a state of thermal equilibrium in which their temperatures will be the same (zero-th law of thermodynamics). 6. The work done on (or by) a system by (or on) its environment, plus the heat given to (or taken from) the system by its environment, always equals the net change in the system’s total energy (conservation of energy, or first law of thermodynamics; Eq. (13.8)). 7. For any system in thermal equilibrium, there exists a state variable, called entropy, with the property that it can never decrease for a closed system. When a system at temperature T takes in a small amount of heat dQ, its change in entropy is given by dS = dQ/T. 8. This principle of never-decreasing entropy is equivalent to the statement that “No process is possible whose sole result is the transfer of heat from a cooler to a hotter body.” 9. The principle 7. is also equivalent to Carnot’s theorem, which states that “it is impossible for an engine that operates in a cycle, taking in heat from a hot reservoir at temperature Th and exhausting heat to a cold reservoir at temperature Tc, to do work with an efficiency greater than 1 −Tc/Th.” 10. Either one of 7., 8., or 9., above, may be regarded as an equivalent statement of the second law of thermodynamics. 11. Carnot’s theorem shows the limitations inherent in the conversion of thermal energy into macroscopic work, which is the reason why one usually regards mechanical energy that is converted into thermal energy as “lost.”
University Physics I Classical Mechanics_Page_337_Chunk4535
320 CHAPTER 13. THERMODYNAMICS 12. Microscopically, the entropy of a system is a measure of the range of distinct states available to its microscopic components (atoms or molecules) that are compatible with the set of macroscopic constraints that determine its thermal equilibrium state. More entropy means a greater range of possible “microstates.” 13. Entropy always increases in irreversible processes.
University Physics I Classical Mechanics_Page_338_Chunk4536
13.6. EXAMPLES 321 13.6 Examples 13.6.1 Calorimetry The specific heat of aluminum is 900 J/kg·K, and that of water is 4186 J·K. Suppose you drop a block of aluminum of mass 1 kg at a temperature of 80◦C in a liter of water (which also has a mass of 1 kg) at a temperature of 20◦C. What is the final temperature of the system, assuming no exchange of heat with the environment takes place? How much energy does the aluminum lose/the water gain? Solution Let us call TAl the initial temperature of the aluminum, Twater the initial temperature of the water, and Tf their final common temperature. The thermal energy given offby the aluminum equals ∆EAl = CAl(Tf −TAl) (this follows from the definition (13.1) of heat capacity; we could equally well call this quantity “the heat given offby the aluminum”). In the same way, the thermal energy change of the water (heat absorbed by the water) equals ∆Ewater = Cwater(Tf −Twater). If the total system is closed, the sum of these two quantities, each with its appropriate sign, must be zero: 0 = ∆EAl + ∆Ewater = CAl(Tf −TAl) + Cwater(Tf −Twater) (13.20) This equation for Tf has the solution Tf = CAlTAl + CwaterTwater CAl + Cwater (13.21) As you can see, the result is a weighted average of the two starting temperatures, with the corre- sponding heat capacities as the weighting factors. The heat capacities C are equal to the given specific heats multiplied by the respective masses. In this case, the mass of aluminum and the mass of the water are the same, so they will cancel in the final result. Also, we can use the temperatures in degrees Celsius, instead of Kelvin. This is not immediately obvious from the final expression (13.21), but if you look at (13.20) you’ll see it involves only temperature differences, and those have the same value in the Kelvin and Celsius scales. Substituting the given values in (13.21), then, we get Tf = 900 × 80 + 4186 × 20 900 + 4186 = 30.6◦C (13.22) This is much closer to the initial temperature of the water, as expected, since it has the greater heat capacity. The amount of heat exchanged is Cwater(Tf −Twater) = 4186 × (30.6 −20) = 44, 440 J = 44.4 kJ (13.23)
University Physics I Classical Mechanics_Page_339_Chunk4537
322 CHAPTER 13. THERMODYNAMICS So, 1 kg of aluminum gives off44.4 kJ of thermal energy and its temperature drops almost 50◦C, from 80◦C to 30.6◦C, whereas 1 kg of water takes in the same amount of thermal energy and its temperature only rises about 10.6◦C. 13.6.2 Equipartition of energy Estimate the speed of an oxygen molecule in air at room temperature (about 300 K). Solution Recall that in Section 13.2.2 I mentioned that the average translational kinetic energy of a molecule in a system at a temperature T is 3 2kBT (Eq. (13.7), where kB, Boltzmann’s constant, is equal to 1.38 × 10−23 J/K. So, at T = 300 K, a molecule of oxygen (or of anything else, for that matter) should have, on average, a kinetic energy of ⟨Ktrans⟩= 3 2kBT = 3 2 × 1.38 × 10−23 × 300 J = 6.21 × 10−21 J (13.24) Since K = 1 2mv2, we can figure out the average value of v2 if we know the mass of an oxygen molecule. This is something you can look up, or derive like this: One mole of oxygen atoms has a mass of 16 grams (16 is the atomic mass number of oxygen) and contains Avogadro’s number of atoms, 6.02 × 1023. So a single atom has a mass of 0.016 kg/6.02 × 1023 = 2.66 × 10−26 kg. A molecule of oxygen contains two atoms, so it has twice the mass, m = 5.32 × 10−26 kg. Then, ⟨v2⟩= 2⟨Ktrans⟩ m = 2 × 6.21 × 10−21 J 5.32 × 10−26 kg = 2.33 × 105 m2 s2 (13.25) The square root of this will give us what is called the “root mean square” velocity, or vrms: vrms = * 2.33 × 105 m2 s2 = 483 m s (13.26) This is of the same order of magnitude as (but larger than) the speed of sound in air at room temperature (about 340 m/s, as you may recall from Chapter 12).
University Physics I Classical Mechanics_Page_340_Chunk4538
13.7. PROBLEMS 323 13.7 Problems Problem 1 Consider a system of two objects in contact, one initially hotter than the other, so they may directly exchange thermal energy, in isolation from the rest of the world. According to the laws of thermodynamics, what must happen to the system’s total energy and entropy? (Do they change, increase, decrease, stay constant. . .?) Problem 2 Consider the same two objects in Problem 1 and suppose the heat capacity of the colder object is much greater than the heat capacity of the hotter one. When the system reaches thermal equilibrium, will its final temperature will be closer to the initial temperature of the hot object, the colder object, or exactly halfway between the two initial temperatures? Why? Problem 3 Which of the following is not a valid formulation of the second law of thermodynamics? (a) For any system in thermal equilibrium, there exists a state variable, called entropy, with the property that it can never decrease for a closed system. (b) No process is possible whose sole result is the transfer of heat from a cooler to a hotter body. (c) It is impossible for an engine that operates in a cycle, taking in heat from a hot reservoir at temperature Th and exhausting heat to a cold reservoir at temperature Tc, to do work with an efficiency greater than 1 −Tc/Th. (d) The entropy of any system goes to zero as T (the absolute, or Kelvin) temperature goes to zero. Problem 4 Which of the following statements is true? (a) Once the entropy of a system increases, it is impossible to bring it back down. (b) Once some amount of mechanical energy is converted to thermal energy, it is impossible to turn any of it back into mechanical energy. (c) It is always possible to reduce the entropy of a system, for instance, by cooling it. (d) All of the above statements are true. (e) None of the above statements are true. Other questions • Can you tell the temperature of a gas by measuring the translational kinetic energy of a single molecule? • Does a shuffled deck of cards have more or less entropy (in the thermodynamic sense) than an identical, ordered set of cards? Assume they are at the same temperature.
University Physics I Classical Mechanics_Page_341_Chunk4539
324 CHAPTER 13. THERMODYNAMICS • A diatomic gas molecule, such as O2, can store kinetic energy in the form of vibrations and rotations, in addition to just translation of the center of mass. By contrast, a monoatomic gas molecule such as C has virtually no kinetic energy (at normal temperatures) other than translational kinetic energy. Which kind of gas do you expect to have a larger molar heat capacity (heat capacity per molecule)?
University Physics I Classical Mechanics_Page_342_Chunk4540
Algorithms and Data Structures With Applications to Graphics and Geometry
algorithms and data structures_Page_1_Chunk4541
This book is licensed under a Creative Commons Attribution 3.0 License Algorithms and Data Structures With Applications to Graphics and Geometry Jurg Nievergelt Klaus Hinrichs Copyright © 2011 Jurg Nievergelt Editor-In-Chief: Jurg Nievergelt Associate Editor: Marisa Drexel Ulrich Editorial Assistants: Jon Durden, Tessa Greenleaf, Kristyna Mauch Selph, Ernesto Serrano For any questions about this text, please email: drexel@uga.edu The Global Text Project is funded by the Jacobs Foundation, Zurich, Switzerland. This book is licensed under a Creative Commons Attribution 3.0 License. Algorithms and Data Structures 2 A Global Text
algorithms and data structures_Page_2_Chunk4542
Table of Contents Part I: Programming environments for motion, graphics, and geometry.................................7 1. Reducing a task to given primitives: programming motion...................................................9 A robot car, its capabilities, and the task to be performed.............................................................................. 9 Wall-following algorithm described informally............................................................................................. 10 Algorithm specified in a high-level language.................................................................................................. 11 Algorithm programmed in the robot's language............................................................................................ 12 The robot's program optimized...................................................................................................................... 12 2. Graphics primitives and environments.................................................................................14 Turtle graphics: a basic environment............................................................................................................. 14 QuickDraw: a graphics toolbox ...................................................................................................................... 16 A graphics frame program.............................................................................................................................. 19 3. Algorithm animation............................................................................................................. 24 Computer-driven visualization: characteristics and techniques................................................................... 24 A gallery of algorithm snapshots.................................................................................................................... 27 Part II: Programming concepts: beyond notation....................................................................33 4. Algorithms and programs as literature: substance and form..............................................34 Programming in the large versus programming in the small........................................................................34 Documentation versus literature: is it meant to be read?..............................................................................35 Pascal and its dialects: lingua franca of computer science............................................................................ 40 5. Divide-and-conquer and recursion.......................................................................................45 An algorithmic principle................................................................................................................................. 45 Divide-and-conquer expressed as a diagram: merge sort............................................................................. 46 Recursively defined trees................................................................................................................................ 47 Recursive tree traversal.................................................................................................................................. 49 Recursion versus iteration: the Tower of Hanoi............................................................................................ 50 The flag of Alfanumerica: an algorithmic novel on iteration and recursion................................................. 52 6. Syntax.....................................................................................................................................53 Syntax and semantics..................................................................................................................................... 53 Grammars and their representation: syntax diagrams and EBNF................................................................ 54 An overly simple syntax for simple expressions.............................................................................................57 Parenthesis-free notation for arithmetic expressions....................................................................................59 7. Syntax analysis.......................................................................................................................62 The role of syntax analysis..............................................................................................................................62 Syntax analysis of parenthesis-free expressions by counting........................................................................63 Analysis by recursive descent......................................................................................................................... 64 Turning syntax diagrams into a parser.......................................................................................................... 65 Part III: Objects, algorithms, programs....................................................................................67 8. Truth values, the data type 'set', and bit acrobatics............................................................. 69 Bits and boolean functions............................................................................................................................. 69 Swapping and crossovers: the versatile exclusive-or..................................................................................... 70 The bit sum or "population count"..................................................................................................................71 9. Ordered sets...........................................................................................................................78 Sequential search............................................................................................................................................ 78 Binary search.................................................................................................................................................. 79 In-place permutation...................................................................................................................................... 82 10. Strings ..................................................................................................................................87 Recognizing a pattern consisting of a single string........................................................................................87 Recognizing a set of strings: a finite-state-machine interpreter................................................................... 88 11. Matrices and graphs: transitive closure...............................................................................93 3
algorithms and data structures_Page_3_Chunk4543
This book is licensed under a Creative Commons Attribution 3.0 License Paths in a graph.............................................................................................................................................. 93 Boolean matrix multiplication....................................................................................................................... 94 Warshall's algorithm....................................................................................................................................... 95 Minimum spanning tree in a graph................................................................................................................ 97 12. Integers...............................................................................................................................100 Operations on integers................................................................................................................................. 100 The Euclidean algorithm.............................................................................................................................. 102 The prime number sieve of Eratosthenes..................................................................................................... 103 Large integers............................................................................................................................................... 104 Modular number systems: the poor man's large integers............................................................................105 Random numbers.......................................................................................................................................... 107 13. Reals....................................................................................................................................110 Floating-point numbers................................................................................................................................ 110 Some dangers................................................................................................................................................. 112 Horner's method............................................................................................................................................ 113 Bisection........................................................................................................................................................ 114 Newton's method for computing the square root......................................................................................... 115 14. Straight lines and circles.....................................................................................................119 Intersection.................................................................................................................................................... 119 Clipping......................................................................................................................................................... 122 Drawing digitized lines................................................................................................................................. 123 The riddle of the braiding straight lines....................................................................................................... 126 Digitized circles ............................................................................................................................................. 131 Part IV: Complexity of problems and algorithms...................................................................134 15. Computability and complexity........................................................................................... 135 Models of computation: the ultimate RISC.................................................................................................. 135 Almost nothing is computable...................................................................................................................... 138 The halting problem is undecidable............................................................................................................. 139 Computable, yet unknown............................................................................................................................ 140 Multiplication of complex numbers............................................................................................................. 142 Complexity of matrix multiplication............................................................................................................ 142 16. The mathematics of algorithm analysis.............................................................................146 Growth rates and orders of magnitude.........................................................................................................146 Asymptotics................................................................................................................................................... 147 Summation formulas.................................................................................................................................... 148 Recurrence relations..................................................................................................................................... 150 Asymptotic performance of divide-and-conquer algorithms....................................................................... 153 Permutations................................................................................................................................................. 154 Trees.............................................................................................................................................................. 155 17. Sorting and its complexity..................................................................................................158 What is sorting? How difficult is it?............................................................................................................. 158 Types of sorting algorithms.......................................................................................................................... 160 Simple sorting algorithms that work in time Θ(n2)..................................................................................... 163 A lower bound Ω(n · log n)............................................................................................................................ 165 Quicksort....................................................................................................................................................... 166 Analysis for three cases: best, "typical", and worst...................................................................................... 169 Is it possible to sort in linear time?............................................................................................................... 174 Sorting networks........................................................................................................................................... 174 Part V: Data structures.............................................................................................................179 18. What is a data structure?...................................................................................................180 Data structures old and new......................................................................................................................... 180 Algorithms and Data Structures 4 A Global Text
algorithms and data structures_Page_4_Chunk4544
The range of data structures studied............................................................................................................ 181 Performance criteria and measures..............................................................................................................182 19. Abstract data types.............................................................................................................184 Concepts: What and why?............................................................................................................................ 184 Stack.............................................................................................................................................................. 185 First-in-first-out queue................................................................................................................................. 189 Priority queue............................................................................................................................................... 190 Dictionary...................................................................................................................................................... 191 20. Implicit data structures..................................................................................................... 196 What is an implicit data structure?.............................................................................................................. 196 Array storage................................................................................................................................................. 197 Implementation of the fixed-length fifo queue as a circular buffer............................................................ 202 Implementation of the fixed-length priority queue as a heap..................................................................... 205 Heapsort ...................................................................................................................................................... 209 21. List structures..................................................................................................................... 211 Lists, memory management, pointer variables ............................................................................................211 The fifo queue implemented as a one-way list ............................................................................................ 214 Tree traversal................................................................................................................................................ 214 Binary search trees....................................................................................................................................... 223 Height-balanced trees.................................................................................................................................. 228 22. Address computation ........................................................................................................239 Concepts and terminology............................................................................................................................ 239 The special case of small key domains ........................................................................................................ 240 The special case of perfect hashing: table contents known a priori ............................................................241 Conventional hash tables: collision resolution ........................................................................................... 242 Choice of hash function: randomization...................................................................................................... 246 Performance analysis .................................................................................................................................. 248 Extendible hashing ...................................................................................................................................... 249 A virtual radix tree: order-preserving extendible hashing.......................................................................... 251 23. Metric data structures....................................................................................................... 254 Organizing the embedding space versus organizing its contents................................................................ 254 Radix trees, tries .......................................................................................................................................... 255 Quadtrees and octtrees ................................................................................................................................ 255 Spatial data structures: objectives and constraints......................................................................................257 The grid file................................................................................................................................................... 259 Simple geometric objects and their parameter spaces................................................................................ 263 Region queries of arbitrary shape................................................................................................................ 264 Evaluating region queries with a grid file.................................................................................................... 267 Interaction between query processing and data access............................................................................... 267 Part VI: Interaction between algorithms and data structures: case studies in geometric computation................................................................................................................................271 24. Sample problems and algorithms..................................................................................... 272 Geometry and geometric computation.........................................................................................................272 Convex hull: a multitude of algorithms........................................................................................................ 273 The uses of convexity: basic operations on polygons................................................................................... 277 Visibility in the plane: a simple algorithm whose analysis is not................................................................ 279 25. Plane-sweep: a general-purpose algorithm for two-dimensional problems illustrated using line segment intersection.......................................................................................................... 286 The line segment intersection test............................................................................................................... 286 The skeleton: Turning a space dimension into a time dimension.............................................................. 288 Data structures............................................................................................................................................. 288 5
algorithms and data structures_Page_5_Chunk4545
This book is licensed under a Creative Commons Attribution 3.0 License Updating the y-table and detecting an intersection.................................................................................... 289 Sweeping across intersections ..................................................................................................................... 290 Degenerate configurations, numerical errors, robustness........................................................................... 291 26. The closest pair..................................................................................................................293 The problem.................................................................................................................................................. 293 Plane-sweep applied to the closest pair problem.........................................................................................294 Implementation............................................................................................................................................ 295 Analysis......................................................................................................................................................... 297 Sweeping in three or more dimensions....................................................................................................... 298 Algorithms and Data Structures 6 A Global Text
algorithms and data structures_Page_6_Chunk4546
Part I: Programming environments for motion, graphics, and geometry Part I of this text book will discuss: • simple programming environments • program design • informal versus formal notations • reducing a solution to primitive operations, and programming as an activity independent of language. The purpose of an artificial programming environment A program can be designed with the barest of tools, paper and pencil, or in the programmer's head. In the realm of such informal environments, a program design may contain vague concepts expressed in an informal notation. Before he or she can execute this program, the programmer needs a programming environment, typically a complex system with many distinct components: a computer and its operating system, utilities, and program libraries; text and program editors; various programming languages and their processors. Such real programming environments force programmers to express themselves in formal notations. Programming is the realization of a solution to a problem, expressed in terms of those operations provided by a given programming environment. Most programmers work in environments that provide very powerful operations and tools. The more powerful a programming environment, the simpler the programming task, at least to the expert who has achieved mastery of this environment. Even an experienced programmer may need several months to master a new programming environment, and a novice may give up in frustration at the multitude of concepts and details he or she must understand before writing the simplest program. The simpler a programming environment, the easier it is to write and run small programs, and the more work it is to write substantial, useful programs. In the early days of computing, before the proliferation of programming languages during the 1960s, most programmers worked in environments that were exceedingly simple by modern standards: Acquaintance with an assembler, a loader, and a small program library sufficed. The programs they wrote were small compared to what a professional programmer writes today. The simpler a programming environment is, the better suited it is for learning to program. Alas, today simple environments are hard to find! Even a home computer is equipped with complex software that is not easily ignored or bypassed. For the sake of education it is useful to invent artificial programming environments. Their only purpose is to illustrate some important concepts in the simplest possible setting and to facilitate insight. Part I of this book introduces such a toy 7
algorithms and data structures_Page_7_Chunk4547
This book is licensed under a Creative Commons Attribution 3.0 License programming environment suitable for programming graphics and motion, and illustrates how it can gradually be enriched to approach a simple but useful graphics environment. Textbooks on computer graphics. The computer-driven graphics screen is a powerful new medium for communication. Visualization often makes it possible to present the results of a computation in intuitively appealing ways that convey insights not easily gained in any other manner. To exploit this medium, every programmer must master basic visualization techniques. We refer the reader interested in a systematic introduction to computer graphics to such excellent textbooks as [BG 89], [FDFH 90], [NS 79], [Rog 85], [Wat 89], and [Wol 89]. Algorithms and Data Structures 8 A Global Text
algorithms and data structures_Page_8_Chunk4548
This book is licensed under a Creative Commons Attribution 3.0 License 1. Reducing a task to given primitives: programming motion Learning objectives: • primitives for specifying motion • expressing an algorithm in informal notations and in high- and low-level programming languages • program verification • program optimization A robot car, its capabilities, and the task to be performed Some aspects of programming can be learned without a computer, by inventing an artificial programming environment as a purely mental exercise. The example of a vehicle that moves under program control in a fictitious landscape is a microcosmos of programming lore. In this section we introduce important concepts that will reappear later in more elaborate settings. The environment. Consider a two-dimensional square grid, a portion of which is enclosed by a wall made up of horizontal and vertical line segments that run halfway between the grid points (Exhibit 1.1). A robot car enclosed within the wall moves along this grid under computer control, one step at a time, from grid point to adjacent grid point. Before and after each step, the robot's state is described by a location (grid point) and a direction (north, east, south, or west). Exhibit 1.1: The robot's crosshairs show its current location on the grid. The robot is controlled by a program that uses the following commands: left Turn 90 degrees counterclockwise. right Turn 90 degrees clockwise. forward Move one step, to the next grid point in front of you goto # Send program control to the label #. if touch goto # If you are touching a wall to your front, send program control to the label #. Algorithms and Data Structures 9 A Global Text
algorithms and data structures_Page_9_Chunk4549
1. Reducing a task to given primitives: programming motion A program for the robot is a sequence of commands with distinct labels. The labels serve merely to identify the commands and need not be arranged either consecutively or in increasing order. Execution begins with the first command and proceeds to successive commands in the order in which they appear, except when flow of control is redirected by either of the goto commands. Example The following program moves the robot forward until it bumps into a wall: 1 if touch goto 4 2 forward 3 goto 1 4 { there is no command here; just a label } In developing programs for the robot, we feel free to use any high-level language we prefer, and embed robot commands in it. Thus we might have expressed our wall-finding program by the simpler statement while not touch do forward; and then translated it into the robot's language. A program for this robot car to patrol the walls of a city consists of two parts: First, find a wall, the problem we just solved. Second, move along the wall forever while maintaining two conditions: 1. Never lose touch with the wall; at all times, keep within one step of it. 2. Visit every spot along the wall in a monotonic progression. The mental image of walking around a room with eyes closed, left arm extended, and the left hand touching the wall at all times will prove useful. To mirror this solution we start the robot so that it has a wall on its immediate left rather than in front. As the robot has no sensor on its left side, we will let it turn left at every step to sense the wall with its front bumper, then turn right to resume its position with the wall to its left. Wall-following algorithm described informally Idea of solution: Touch the wall with your left hand; move forward, turning left or right as required to keep touching the wall. Wall-following algorithm described in English: Clockwise, starting at left, look for the first direction not blocked by a wall, and if found, take a step in that direction. Let us test this algorithm on some critical configurations. The robot inside a unit square turns forever, never finding a direction to take a step (Exhibit 1.2). In Exhibit 1.3 the robot negotiates a left-hand spike. After each step, there is a wall to its left-rear. In Exhibit 1.4 the robot enters a blind alley. At the end of the alley, it turns clockwise twice, then exits by the route it entered. Exhibit 1.2: Robot in a box spins on its heels. 10
algorithms and data structures_Page_10_Chunk4550
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 1.3: The robot turns around a spike. Exhibit 1.4: Backing up in a blind alley. Algorithm specified in a high-level language The ideas presented informally in above section are made precise in the following elegant, concise program: { wall to left-rear } loop { wall to left-rear } left; { wall to left-front } while touch do { wall to right-front } right; { wall to left-front } endwhile; { wall to left-front } forward; { wall to left-rear } forever; { wall to left-rear } Program verification. The comments in braces are program invariants: Assertions about the state of the robot that are true every time the flow of control reaches the place in the program where they are written. We need three types of invariants to verify the wall-following program: "wall to left-rear", "wall to left-front", and "wall to right-front". The relationships between the robot's position and the presence of a nearby wall that must hold for each assertion to be true are illustrated in Exhibit 1.5. Shaded circles indicate points through which a wall must pass. Each robot command transforms its precondition (i.e. the assertion true before the command is executed) into its postcondition (i.e. the assertion true after its execution). Thus each of the commands 'left', 'right', and 'forward' is a predicate transformer, as suggested in Exhibit 1.6. Exhibit 1.5: Three types of invariants relate the positions of robot and wall. Algorithms and Data Structures 11 A Global Text
algorithms and data structures_Page_11_Chunk4551
1. Reducing a task to given primitives: programming motion Exhibit 1.6: Robot motions as predicate transformers. Algorithm programmed in the robot's language A straightforward translation from the high-level program into the robot's low-level language yields the following seven-line wall-following program: loop left; 1 left while touch do 2 if touch goto 4 3 goto 6 right; 4 right endwhile; 5 goto 2 forward; 6 forward forever; 7 goto 1 The robot's program optimized In designing a program it is best to follow simple, general ideas, and to decide on details in the most straightforward manner, without regard for the many alternative ways that are always available for handling details. Once a program is proven correct, and runs, then we may try to improve its efficiency, measured by time and memory requirements. This process of program transformation can often be done syntactically, that is merely by considering the definition of individual statements, not the algorithm as a whole. As an example, we derive a five-line version of the wall-following program by transforming the seven-line program in two steps. If we have the complementary primitive 'if not touch goto #', we can simplify the flow of the program at the left as shown on the right side. { wall to left-rear } { wall to left-rear } 1 left 1 left 2 if touch goto 4 2 if not touch goto 6 3 goto 6 { wall to right-front } { wall to right-front } 4 right 4 right 12
algorithms and data structures_Page_12_Chunk4552
This book is licensed under a Creative Commons Attribution 3.0 License 5 goto 2 5 goto 2 6 forward 6 forward 7 goto 1 7 goto 1 An optimization technique called loop rotation allows us to shorten this program by yet another instruction. It changes the structure of the program significantly, as we see from the way the labels have been permuted. The assertion "wall to right-front" attached to line 4 serves as an invariant of the loop "keep turning right while you can't advance". { wall to right-front } 4 right 2 if touch goto 4 6 forward 1 left 7 goto 2 Programming projects 1. Design a data structure suitable for storing a wall made up of horizontal and vertical line segments in a square grid of bounded size. Write a "wall-editor", i.e. an interactive program that lets the user define and modify an instance of such a wall. 2. Program the wall-following algorithm and animate its execution when tracking a wall entered with the wall- editor. Specifically, show the robot's position and orientation after each change of state. Algorithms and Data Structures 13 A Global Text
algorithms and data structures_Page_13_Chunk4553
This book is licensed under a Creative Commons Attribution 3.0 License 2. Graphics primitives and environments Learning objectives: • turtle graphics • QuickDraw: A graphics toolbox • frame program • interactive graphics input/output • example: polyline input Turtle graphics: a basic environment Seymour Papert [Pap80] introduced the term turtle graphics to denote a set of primitives for line drawing. Originally implemented in the programming language Logo, turtle graphics primitives are now available for several computer systems and languages. They come in different versions, but the essential point is the same as that introduced in the example of the robot car: The pen (or "turtle") is a device that has a state (position, direction) and is driven by incremental operations “move” and “turn” that transform the turtle to a new state depending on its current state: move(s) { take s unit steps in the direction you are facing } turn(d) { turn counterclockwise d degrees } The turtle's initial state is set by the following operations: moveto(x,y) { move to the position (x,y) in absolute coordinates } turnto(d) { face d degrees from due east } In addition, we can specify the color of the trail drawn by the moving pen: pencolor(c) { where c = white, black, none, etc. } Example The following program fragment approximates a circle tangential to the x-axis at the origin by drawing a 36- sided polygon: moveto(0, 0); { position pen at origin } turnto(0); { face east } step := 7; { arbitrarily chosen step length } do 36 times { 36 sides · 10° = 360° } { move(step); turn(10) } { 10 degrees counterclockwise } In graphics programming we are likely to use basic figures, such as circles, over and over again, each time with a different size and position. Thus we wish to turn a program fragment such as the circle approximation above into a reusable procedure. Algorithms and Data Structures 14 A Global Text
algorithms and data structures_Page_14_Chunk4554
2. Graphics primitives and environments Procedures as building blocks A program is built from components at many different levels of complexity. At the lowest level we have the constructs provided by the language we use: constants, variables, operators, expressions, and simple (unstructured) statements. At the next higher level we have procedures: they let us refer to a program fragment of arbitrary size and complexity as a single entity, and build hierarchically nested structures. Modern programming languages provide yet another level of packaging: modules, or packages, useful for grouping related data and procedures. We limit our discussion to the use of procedures. Programmers accumulate their own collection of useful program fragments. Programming languages provide the concept of a procedure as the major tool for turning fragments into reusable building blocks. A procedure consists of two parts with distinct purposes: 1. The heading specifies an important part of the procedure's external behavior through the list of formal parameters: namely, what type of data moves in and out of the procedure. 2. The body implements the action performed by the procedure, processing the input data and generating the output data. A program fragment that embodies a single coherent concept is best written as a procedure. This is particularly true if we expect to use this fragment again in a different context. The question of how general we want a procedure to be deserves careful thought. If the procedure is too specific, it will rarely be useful. If it is too general, it may be unwieldy: too large, too slow, or just too difficult to understand. The generality of a procedure depends primarily on the choice of formal parameters. Example: the long road toward a procedure “circle” Let us illustrate these issues by discussing design considerations for a procedure that draws a circle on the screen. The program fragment above for drawing a regular polygon is easily turned into procedure ngon(n,s: integer); { n = number of sides, s = step size } var i,j: integer; begin j := 360 div n; for i := 1 to n do { move(s); turn(j) } end; But, a useful procedure to draw a circle requires additional arguments. Let us start with the following: procedure circle(x, y, r, n: integer); { centered at (x, y); r = radius; n = number of sides } var a, s, i: integer; { angle, step, counter } begin moveto(x, y – r); { bottom of circle } turnto(0); { east } a := 360 div n; s := r · sin(a); { between inscribed and circumscribed polygons } for i := 1 to n do { move(s); turn(a) } end; This procedure places the burden of choosing n on the programmer. A more sophisticated, "adaptive" version might choose the number of sides on its own as a function of the radius of the circle to be drawn. We assume that lengths are measured in terms of pixels (picture elements) on the screen. We observe that a circle of radius r is of 15
algorithms and data structures_Page_15_Chunk4555
This book is licensed under a Creative Commons Attribution 3.0 License length 2πr. We approximate it by drawing short-line segments, about 3 pixels long, thus needing about 2·r line segments. procedure circle(x, y, r: integer); { centered at (x, y); radius r} var a, s, i: integer; { angle, step, counter } begin moveto(x, y – r); { bottom of circle } turnto(0); { east } a := 180 div r; { 360 / (# of line segments) } s := r · sin(a); { between inscribed and circumscribed polygons } for i := 1 to 2 · r do { move(s); turn(a) } end; This circle procedure still suffers from severe shortcomings: 1. If we discretize a circle by a set of pixels, it is an unnecessary detour to do this in two steps as done above: first, discretize the circle by a polygon; second, discretize the polygon by pixels. This two-step process is a source of unnecessary work and errors. 2. The approximation of the circle by a polygon computed from vertex to vertex leads to rounding errors that accumulate. Thus the polygon may fail to close, in particular when using integer computation with its inherent large rounding error. 3. The procedure attempts to draw its circle on an infinite screen. Computer screens are finite, and attempted drawing beyond the screen boundary may or may not cause an error. Thus the circle ought to be clipped at the boundaries of an arbitrarily specified rectangle. Writing a good circle procedure is a demanding task for professionals. We started this discussion of desiderata and difficulties of a simple library procedure so that the reader may appreciate the thought and effort that go into building a useful programming environment. In chapter 14 we return to this problem and present one possible goal of "the long road toward a procedure 'circle'". We now make a huge jump from the artificially small environments discussed so far to one of today's realistic programming environments for graphics QuickDraw: a graphics toolbox For the sake of concreteness, the next few sections show programs written for a specific programming environment: MacPascal using the QuickDraw library of graphics routines [App 85]. It is not our purpose to duplicate a manual, but only to convey the flavor of a realistic graphics package and to explain enough about QuickDraw for the reader to understand the few programs that follow. So our treatment is highly selective and biased. Concerning the circle that we attempted to program above, QuickDraw offers five procedures for drawing circles and related figures: procedure FrameOval(r: Rect); procedure PaintOval(r: Rect); procedure EraseOval(r: Rect); procedure InvertOval(r: Rect); procedure FillOval(r: Rect; pat: Pattern); Each one inscribes an oval in an aligned rectangle r (sides parallel to the axes) so as to touch the four sides of r. If r is a square, the oval becomes a circle. We quote from [App 85]: Algorithms and Data Structures 16 A Global Text
algorithms and data structures_Page_16_Chunk4556
2. Graphics primitives and environments FrameOval draws an outline just inside the oval that fits inside the specified rectangle, using the current grafPort's pen pattern, mode, and size. The outline is as wide as the pen width and as tall as the pen height. It's drawn with the pnPat, according to the pattern transfer mode specified by pnMode. The pen location is not changed by this procedure. Right away we notice a trade-off when comparing QuickDraw to the simple turtle graphics environment we introduced earlier. At one stroke, “FrameOval” appears to be able to produce many different pictures, but before we can exploit this power, we have to learn about grafPorts, pen width, pen height, pen patterns, and pattern transfer modes. 'FrameOval' draws the perimeter of an oval, 'PaintOval' paints the interior as well, 'EraseOval' paints an oval with the current grafPort's background pattern, 'InvertOval' complements the pixels: 'white' becomes 'black', and vice versa. 'FillOval' has an additional argument that specifies a pen pattern used for painting the interior. We may not need to know all of this in order to use one of these procedures, but we do need to know how to specify a rectangle. QuickDraw has predefined a type 'Rect' that, somewhat ambiguously at the programmer's choice, has either of the following two interpretations: type Rect = record top, left, bottom, right: integer end; type Rect = record topLeft, botRight: Point end; with one of the interpretations of type 'Point' being type Point = record v, h: integer end; Exhibit 2.1 illustrates and provides more information about these concepts. It shows a plane with first coordinate v that runs from top to bottom, and a second coordinate h that runs from left to right. (The reason for v running from top to bottom, rather than vice versa as used in math books, is compatibility with text coordinates where lines are naturally numbered from top to bottom.) The domain of v and h are the integers from –215= –32768 to 215– 1 = 32767. The points thus addressed on the screen are shown as intersections of grid lines. These lines and grid points are infinitely thin - they have no extension. The pixels are the unit squares between them. Each pixel is paired with its top left grid point. This may be enough information to let us draw a slightly fat point of radius 3 pixels at the grid point with integer coordinates (v, h) by calling PaintOval(v – 3, h – 3, v + 3, h + 3); Exhibit 2.1: Screen coordinates define the location of pixels. To understand the procedures of this section, the reader has to understand a few details about two key aspects of interactive graphics: • timing and synchronization of devices and program execution • how screen pictures are controlled at the pixel level 17
algorithms and data structures_Page_17_Chunk4557
This book is licensed under a Creative Commons Attribution 3.0 License Synchronization In interactive applications we often wish to specify a grid point by letting the user point the mouse-driven cursor to some spot on the screen. The 'procedure GetMouse(v, h)' returns the coordinates of the grid point where the cursor is located at the moment 'GetMouse' is executed. Thus we can track and paint the path of the mouse by a loop such as repeat GetMouse(v, h); PaintOval(v – 3, h – 3, v + 3, h + 3) until stop; This does not give the user any timing control over when he or she wants the computer to read the coordinates of the mouse cursor. Clicking the mouse button is the usual way to tell the computer "Now!". A predefined boolean function 'Button' returns 'true' when the mouse button is depressed, 'false' when not. We often synchronize program execution with the user's clicks by programming busy waiting loops: repeat until Button; { waits for the button to be pressed } while Button do; { waits for the button to be released } The following procedure waits for the next click: procedure waitForClick; begin repeat until Button; while Button do end; Pixel acrobatics The QuickDraw pen has four parameters that can be set to draw lines or paint textures of great visual variety: pen location 'pnLoc', pen size 'pnSize' (a rectangle of given height and width), a pen pattern 'pnPat', and a drawing mode 'pnMode'. The pixels affected by a motion of the pen are shown in Exhibit 2.2. Exhibit 2.2: Footprint of the pen. Predefined values of 'pnPat' include 'black', 'gray', and 'white'. 'pnPat' is set by calling the predefined 'procedure PenPat(pat: Pattern)' [e.g. 'PenPat(gray)']. As 'white' is the default background, drawing in 'white' usually serves for erasing. The result of drawing also depends critically on the transfer mode 'pnMode', whose values include 'patCopy', 'patOr', and 'patXor'. A transfer mode is a boolean operation executed in parallel on each pair of pixels in corresponding positions, one on the screen and one in the pen pattern. • 'patCopy' uses the pattern pixel to overwrite the screen pixel, ignoring the latter's previous value; it is the default and most frequently used transfer mode. • 'patOr' paints a black pixel if either or both the screen pixel or the pattern pixel were black; it progressively blackens the screen. Algorithms and Data Structures 18 A Global Text
algorithms and data structures_Page_18_Chunk4558
2. Graphics primitives and environments • 'patXor' (exclusive-or, also known as "odd parity") sets the result to black iff exactly one of (screen pixel, pattern pixel) is black. A white pixel in the pen leaves the underlying screen pixel unchanged; a black pixel complements it. Thus a black pen inverts the screen. 'pnMode' is set by calling the predefined 'procedure PenMode(mode: integer)' [e.g. 'PenMode(patXor)']. The meaning of the remaining predefined procedures our examples use, such as 'MoveTo' and 'LineTo', is easily guessed. So we terminate our peep into some key details of a powerful graphics package, and turn to examples of its use. A graphics frame program Reusable software is a time saving concept that can be practiced profitably in the small. We keep a program that contains nothing but a few of the most useful input/output procedures, displays samples of their results, and conducts a minimal dialog so that the user can step through its execution. We call this a frame program because its real purpose is to facilitate development and testing of new procedures by embedding them in a ready-made, tested environment. A simple frame program like the one below makes it very easy for a novice to write his first interactive graphics program. This particular frame program contains procedures 'GetPoint', 'DrawPoint', 'ClickPoint', 'DrawLine', 'DragLine', 'DrawCircle', and 'DragCircle' for input and display of points, lines, and circles on a screen idealized as a part of a Euclidean plane, disregarding the discretization due to the raster screen. Some of these procedures are so short that one asks why they are introduced at all. 'GetPoint', for example, only converts integer mouse coordinates v, h into a point p with real coordinates. It enables us to refer to a point p without mentioning its coordinates explicitly. Thus, by bringing us closer to standard geometric notation, 'GetPoint' makes programs more readable. The procedure 'DragLine', on the other hand, is a very useful routine for interactive input of line segments. It uses the rubber-band technique, which is familiar to users of graphics editors. The user presses the mouse button to fix the first endpoint of a line segment, and keeps it depressed while moving the mouse to the desired second endpoint. At all times during this motion the program keeps displaying the line segment as it would look if the button were released at that moment. This rubber band keeps getting drawn and erased as it moves across other objects on the screen. The user should study a key detail in the procedure 'DragLine' that prevents other objects from being erased or modified as they collide with the ever-refreshed rubber band: We temporarily set 'PenMode(patXor)'. We encourage you to experiment by modifying this procedure in two ways: 1. Change the first call of the 'procedure DrawLine(L.p1, L.p2, black)' to 'DrawLine(L.p1, L.p2, white)'. You will have turned the procedure 'DragLine' into an artful, if somewhat random, painting brush. 2. Remove the call 'PenMode(patXor)' (thus reestablishing the default 'pnMode = patCopy'), but leave the first 'DrawLine(L.p1, L.p2, white)', followed by the second 'DrawLine(L.p1, L.p2, black)'. You now have a naive rubber-band routine: It alternates erasing (draw 'white') and drawing (draw 'black') the current rubber band, but in so doing it modifies other objects that share pixels with the rubber band. This is our first example of the use of the versatile exclusive-or; others will follow later in the book. program Frame; { provides mouse input and drawing of points, line segments, circles } type point = record x, y: real end; lineSegment = record p1, p2: point { endpoints } end; 19
algorithms and data structures_Page_19_Chunk4559
This book is licensed under a Creative Commons Attribution 3.0 License var c, p: point; r: real; { radius of a circle } L: lineSegment; procedure WaitForClick; begin repeat until Button; while Button do end; procedure GetPoint (var p: point); var v, h: integer; begin GetMouse(v, h); p.x := v; p.y := h { convert integer to real } end; procedure DrawPoint(p: point; pat: Pattern); const t = 3; { radius of a point } begin PenPat(pat); PaintOval(round(p.y) – t, round(p.x) – t, round(p.y) + t, round(p.x) + t) end; procedure ClickPoint(var p: point); begin WaitForClick; GetPoint(p); DrawPoint(p, Black) end; function Dist(p, q: point): real; begin Dist := sqrt(sqr(p.x – q.x) + sqr(p.y – q.y)) end; procedure DrawLine(p1, p2: point; pat: Pattern); begin PenPat(pat); MoveTo(round(p1.x), round(p1.y)); LineTo(round(p2.x), round(p2.y)) end; procedure DragLine(var L: lineSegment); begin repeat until Button; GetPoint(L.p1); L.p2 := L.p1; PenMode(patXor); while Button do begin DrawLine(L.p1, L.p2, black); { replace 'black' by 'white' above to get an artistic drawing tool } GetPoint(L.p2); DrawLine(L.p1, L.p2, black) end; PenMode(patCopy) end; { DragLine } procedure DrawCircle(c: point; r: real; pat: Pattern); begin PenPat(pat); FrameOval(round(c.y – r), round(c.x – r), round(c.y + r), round(c.x + r)) end; procedure DragCircle(var c: point; var r: real); var p: point; begin repeat until Button; GetPoint(c); r := 0.0; PenMode(patXor); while Button do begin DrawCircle(c, r, black); GetPoint(p); Algorithms and Data Structures 20 A Global Text
algorithms and data structures_Page_20_Chunk4560
2. Graphics primitives and environments r := Dist(c, p); DrawCircle(c, r, black); end; PenMode(patCopy) end; { DragCircle } procedure Title; begin ShowText; { make sure the text window and … } ShowDrawing; { … the graphics window show on the screen } WriteLn('Frame program'); WriteLn('with simple graphics and interaction routines.'); WriteLn('Click to proceed.'); WaitForClick end; { Title } procedure What; begin WriteLn('Click a point in the drawing window.'); ClickPoint(p); WriteLn('Drag mouse to enter a line segment.'); DragLine(L); WriteLn('Click center of a circle and drag its radius'); DragCircle(c, r) end; { What } procedure Epilog; begin WriteLn('Bye.') end; begin { Frame } Title; What; Epilog end. { Frame } Example of a graphics routine: polyline input Let us illustrate the use of the frame program above in developing a new graphics procedure. We choose interactive polyline input as an example. A polyline is a chain of directed straight-line segments—the starting point of the next segment coincides with the endpoint of the previous one. 'Polyline' is the most useful tool for interactive input of most drawings made up of straight lines. The user clicks a starting point, and each subsequent click extends the polyline by another line segment. A double click terminates the polyline. We developed 'PolyLine' starting from the frame program above, in particular the procedure 'DragLine', modifying and adding a few procedures. Once 'Polyline' worked, we simplified the frame program a bit. For example, the original frame program uses reals to represent coordinates of points, because most geometric computation is done that way. A polyline on a graphics screen only needs integers, so we changed the type 'point' to integer coordinates. At the moment, the code for polyline input is partly in the procedure 'NextLineSegment' and in the procedure 'What'. In the next iteration, it would probably be combined into a single self-contained procedure, with all the subprocedures it needs, and the frame program would be tossed out—it has served its purpose as a development tool. program PolyLine; { enter a chain of line segments and compute total length } { stop on double click } type point = record x, y: integer; end; var stop: boolean; length: real; 21
algorithms and data structures_Page_21_Chunk4561
This book is licensed under a Creative Commons Attribution 3.0 License p, q: point; function EqPoints (p, q: point): boolean; begin EqPoints := (p.x = q.x) and (p.y = q.y) end; function Dist (p, q: point): real; begin Dist := sqrt(sqr(p.x – q.x) + sqr(p.y – q.y)) end; procedure DrawLine (p, q: point; c: Pattern); begin PenPat(c); MoveTo(p.x, p.y); LineTo(q.x, q.y) end; procedure WaitForClick; begin repeat until Button; while Button do end; procedure NextLineSegment (var stp, endp: point); begin endp := stp; repeat DrawLine(stp, endp, black); { Try 'white' to generate artful pictures! } GetMouse(endp.x, endp.y); DrawLine(stp, endp, black) until Button; while Button do end; { NextLineSegment } procedure Title; begin ShowText; ShowDrawing; WriteLn('Click to start a polyline.'); WriteLn('Click to end each segment.'); WriteLn('Double click to stop.') end; { Title } procedure What; begin WaitForClick; GetMouse(p.x, p.y); stop := false; length := 0.0; PenMode(patXor); while not stop do begin NextLineSegment(p, q); stop := EqPoints(p, q); length := length + Dist(p, q); p := q end end; { What } procedure Epilog; begin WriteLn('Length of polyline = ', length); WriteLn('Bye.') end; begin { PolyLine } Title; What; Epilog end. { PolyLine } Programming projects 1. Implement a simple package of turtle graphics operations on top of the graphics environment available on your computer. 2. Use this package to implement and test a procedure 'circle' that meets the requirements listed at the end of the section “Turtle graphics: a basic environment”. Algorithms and Data Structures 22 A Global Text
algorithms and data structures_Page_22_Chunk4562
2. Graphics primitives and environments 3. Implement your personal graphics frame program as described in “A graphics frame program”. Your effort will pay off in time saved later, as you will be using this program throughout the entire course. 23
algorithms and data structures_Page_23_Chunk4563
This book is licensed under a Creative Commons Attribution 3.0 License 3. Algorithm animation I hear and I forget, I see and I remember, I do and I understand. A picture is worth a thousand words—the art of presenting information in visual form. Learning objectives: • adding animation code to a program • examples of algorithm snapshots Computer-driven visualization: characteristics and techniques The computer-driven graphics screen is a powerful new communications medium; indeed, it is the only two-way mass communications medium we know. Other mass communications media–the printed e.g. recorded audio and video—are one-way streets suitable for delivering a monolog. The unique strength of our new medium is interactive presentation of information. Ideally, the viewer drives the presentation, not just by pushing a start button and turning a channel selector, but controls the presentation at every step. He controls the flow not only with commands such as "faster", "slower", "repeat", "skip", "play this backwards", but more important, with a barrage of "what if?" questions. What if the area of this triangle becomes zero? What if we double the load on this beam? What if world population grows a bit faster? This powerful new medium challenges us to use it well. When using any medium, we must ask: What can it do well, and what does it do poorly? The computer-driven screen is ideally suited for rapid and accurate display of information that can be deduced from large amounts of data by means of straightforward algorithms and lengthy computation. It can do so in response to a variety of user inputs as long as this variety is contained in an algorithmically tractable, narrow domain of discourse. It is not adept at tasks that require judgment, experience, or insight. By comparison, a speaker at the blackboard is slow and inaccurate and can only call upon small amounts of data and tiny computations; we hope she makes up for this technical shortcoming by good judgment, teaching experience, and insight into the subject. By way of another comparison, books and films may accurately and rapidly present results based on much data and computation, but they lack the ability to react to a user's input. Algorithm animation, the technique of displaying the state of programs in execution, is ideally suited for presentation on a graphics screen. There is a need for this type of computation, and there are techniques for producing them. The reasons for animating programs in execution fall into two major categories, which we label checking and exploring. Checking To understand an algorithm well, it is useful to understand it from several distinct points of view. One of them is the static point of view on which correctness proofs are based: Formulate invariants on the data and show that these are preserved under the program's operations. This abstract approach appeals to our rational mind. A second, equally important point of view, is dynamic: Watch the algorithm go through its paces on a variety of input data. This concrete approach appeals to our intuition. Whereas the static approach relies mainly on "thinking", the dynamic approach calls mostly for "doing" and "perceiving", and thus is a prime candidate for visual human- Algorithms and Data Structures 24 A Global Text
algorithms and data structures_Page_24_Chunk4564
3. Algorithm animation computer interaction. In this use of algorithm animation, the user may be checking his understanding of the algorithm, or may be checking the algorithm's correctness—in principle, he could reason this out, but in practice, it is faster and safer to have the computer animation as a double check. Exploring In a growing number of applications, computer visualization cannot be replaced by any other technique. This is the case, for example, in exploratory data analysis, where a scientist may not know a priori what she is looking for, and the only way to look at a mass of data is to generate pictures from it (see a special issue on scientific visualization [Nie 89]). At times static pictures will do, but in simulations (e.g. of the onset of turbulent flow) we prefer to see an animation over time. Turning to the techniques of animation, computer technology is in the midst of extremely rapid evolution toward ever-higher-quality interactive image generation on powerful graphics workstations (see [RN 91] for a survey of the state of the art). Fortunately, animating algorithms such as those presented in this book can be done adequately with the graphics tools available on low-cost workstations. These algorithms operate on discrete data configurations (such as matrices, trees, graphs), and use standard data structures, such as arrays and lists. For such limited classes of algorithms, there are software packages that help produce animations based on specifications, with a minimum of extra programming required. An example of an algorithm animation environment is the BALSA system [Bro 88, BS 85]. A more recent example is the XYZ GeoBench, which animates geometric algorithms [NSDAB 91]. In our experience, the bottleneck of algorithm animation is not the extra code required, but graphic design. What do you want to show, and how do you display it, keeping in mind the limitations of the system you have to work with? The key point to consider is that data does not look like anything until we have defined a mapping from the data space into visual space. Defining such a mapping ranges from trivial to practically impossible. 1. For some kinds of data, such as geometric data in two- and three-dimensional space, or real-valued functions of one or two real variables, there are natural mappings that we learned in school. These help us greatly in getting a feel for the data. 2. Multidimensional data (dimension ≥ 3) can be displayed on a two-dimensional screen using a number of straight forward techniques, such as projections into a subspace, or using color or gray level as a fourth dimension. But our power of perception diminishes rapidly with increasing dimensionality. 3. For discrete combinatorial data there is often no natural or accepted visual representation. As an example, we often draw a graph by mapping nodes into points and edges into lines. This representation is natural for graphs that are embedded in Euclidean space, such as a road network, and we can readily make sense of a map with thousands of cities and road links. When we extend it to arbitrary graphs by placing a node anywhere on the screen, on the other hand, we get a random crisscrossing of lines of little intuitive value. In addition to such inherent problems of visual representation, practical difficulties of the most varied type abound. Examples: • Some screens are awfully small, and some data sets are awfully large for display even on the largest screens. • An animation has to run within a narrow speed range. If it is too fast, we fail to follow, or the screen may flicker disturbingly; if too slow, we may lack the time to observe it. 25
algorithms and data structures_Page_25_Chunk4565
This book is licensed under a Creative Commons Attribution 3.0 License In conclusion, we hold that it is not too difficult to animate simple algorithms as discussed here by interspersing drawing statements into the normal code. Independent of the algorithm to be animated, you can call on your own collection of display and interaction procedures that you have built up in your frame program (in the section "A graphics frame program). But designing an adequate graphic representation is hard and requires a creative effort for each algorithm—that is where animators/programmers will spend the bulk of their effort. More on this topic in [NVH 86]. Example: the convex hull of points in the plane The following program is an illustrative example for algorithm animation. 'ConvexHull' animates an on-line algorithm that constructs half the convex hull (say, the upper half) of a set of points presented incrementally. It accepts one point at a time, which must lie to the right of all preceding ones, and immediately extends the convex hull. The algorithm is explained in detail in “sample problems and algorithms”. program ConvexHull; { of n ≤ 20 points in two dimensions } const nmax = 19; { max number of points } r = 3; { radius of point plot } 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 } procedure PointZero; begin n := 0; x[0] := 5; y[0] := 20; { the first point at fixed location } dx[0] := 0; dy[0] := 1; { assume vertical tangent } b[0] := 0; { points back to itself } PaintOval(y[0] – r, x[0] – r, y[0] + r, x[0] + r) end; function NextRight: boolean; begin if n ≥ nmax then NextRight := false else begin repeat until Button; while Button do GetMouse(px, py); if px ≤ x[n] then NextRight := false else begin PaintOval(py – r, px – r, py + r, px + r); n := n + 1; x[n] := px; y[n] := py; dx[n] := x[n] – x[n – 1]; { dx > 0 } dy[n] := y[n] – y[n –1]; b[n] := n – 1; MoveTo(px, py); Line(–dx[n], –dy[n]); NextRight := true end end end; procedure ComputeTangent; 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] } Algorithms and Data Structures 26 A Global Text
algorithms and data structures_Page_26_Chunk4566
3. Algorithm animation i := b[i]; 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; procedure Title; begin ShowText; ShowDrawing; { make sure windows lie on top } WriteLn('The convex hull'); WriteLn('of n points in the plane sorted by x-coordinate'); WriteLn('is computed in linear time.'); Write('Click next point to the right, or Click left to quit.') end; begin { ConvexHull } Title; PointZero; while NextRight do ComputeTangent; Write('That's it!') end. A gallery of algorithm snapshots The screen dumps shown in Exhibit 3.1 were taken from demonstration programs that we use to illustrate topics discussed in class. Although snapshots cannot convey the information and the impact of animations, they may give the reader ideas to try out. We select two standard algorithm animation topics (sorting and random number generation), and an example showing the effect of cumulative rounding errors. Exhibit 3.1: Initial configuration of data, … 27
algorithms and data structures_Page_27_Chunk4567
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 3.1: … and snapshots from two sorting algorithms. Visual test for randomness Our visual system is amazingly powerful at detecting patterns of certain kinds in the midst of noise. Random number generators (RNGs) are intended to simulate "noise" by means of simple formulas. When patterns appear in the visual representation of supposedly random numbers, chances are that this RNG will also fail more rigorous statistical tests. The eyes' pattern detection ability serves well to disqualify a faulty RNG but cannot certify one as adequate. Exhibit 3.2 shows a simulation of the Galton board. In theory, the resulting density diagram should approximate a bellshaped Gaussian distribution. Obviously, the RNG used falls short of expectations. Exhibit 3.2: One look suffices to unmask a bad RNG. Numerics of chaos, or chaos of numerical computation? The following example shows the effect of rounding errors and precision in linear recurrence relations. The d- step linear recurrence with constant coefficients in the domain of real or complex numbers, Algorithms and Data Structures 28 A Global Text
algorithms and data structures_Page_28_Chunk4568
3. Algorithm animation is one of the most frequent formulas evaluated in scientific and technical computation (e.g. for the solution of differential equations). By proper choice of the constants ci and of initial values z0, z1, … , zd–1 we can generate sequences zk that when plotted in the plane of complex numbers form many different figures. With d= 1 and |χ 1|= 1, for example, we generate circles. The pictures in Exhibit 3.3 were all generated with d = 3 and conditions that determine a curve that is most easily described as a circle 3 running around the perimeter of another circle 2 that runs around a stationary circle 1. We performed this computation with a floating-point package that lets us pick precision P (i.e. the number of bits in the mantissa). The resulting pictures look a bit chaotic, with a behavior we have come to associate with fractals—even if the mathematics of generating them is completely different, and linear recurrences computed without error would look much more regular. Notice that the first two images are generated by the same formula, with a single bit of difference in the precision used. The whim of this 1-bit difference in precision changes the image entirely. 29
algorithms and data structures_Page_29_Chunk4569
This book is licensed under a Creative Commons Attribution 3.0 License Algorithms and Data Structures 30 A Global Text
algorithms and data structures_Page_30_Chunk4570
3. Algorithm animation Exhibit 3.3: The effect of rounding errors in linear recurrence relations. Programming projects 1. Use your personal graphics frame program (the programming project of “graphics primitives and environments”) to implement and animate the convex hull algorithm example. 31
algorithms and data structures_Page_31_Chunk4571
This book is licensed under a Creative Commons Attribution 3.0 License 2. Use your graphics frame program to implement and animate the behavior of recurrence relations as discussed in the section “A gallery of algorithm snapshots”. 3. Extend your graphics frame program with a set of dialog control operations sufficient to guide the user through the various steps of the animation of recurrence relations: in particular, to give him the options, at any time, to enter a new set of parameters, then execute the algorithm and animate it in either 'movie mode' (it runs at a predetermined speed until stopped by the user), or 'step mode' [the display changes only when the user enters a logical command 'next' (e.g. by clicking the mouse or hitting a specific key)]. Algorithms and Data Structures 32 A Global Text
algorithms and data structures_Page_32_Chunk4572
This book is licensed under a Creative Commons Attribution 3.0 License Part II: Programming concepts: beyond notation Thoughts on the role of programming notations A programming language is the main interface between a programmer and the physical machine, and a novice programmer will tend to identify "programming" with "programming in the particular language she has learned". The realization that there is much to programming "beyond notation" (i.e. principles that transcend any one language) is a big step forward in a programmer's development. Part II aims to help the reader take this step forward. We present examples that are best understood by focusing on abstract principles of algorithm design, and only later do we grope for suitable notations to turn this principle into an algorithm expressed in sufficient detail to become executable. In keeping with our predilection for graphic communication, the first informal expression of an algorithmic idea is often pictorial. We show by example how such representations, although they may be incomplete, can be turned into programs in a formal notation. The literature on programming and languages. There are many books that present principles of programming and of programming languages from a higher level of abstraction. The principles highlighted differ from author to author, ranging from intuitive understanding to complete formality. The following textbooks provide an excellent sample from the broad spectrum of approaches: [ASS 84], [ASU 86], [Ben 82], [Ben 85], [Ben 88], [Dij 76], [DF 88], [Gri 81], and [Mey 90]. Algorithms and Data Structures 33 A Global Text
algorithms and data structures_Page_33_Chunk4573
This book is licensed under a Creative Commons Attribution 3.0 License 4. Algorithms and programs as literature: substance and form Learning objectives: • programming in the large versus programming in the small • large flat programs versus small deep programs • programs as literature • fractal pictures: snowflakes and Hilbert's space-filling curve • recursive definition of fractals by production or rewrite rules • Pascal and programming notations Programming in the large versus programming in the small In studying and discussing the art of programming it is useful to distinguish between large programs and small programs, since these two types impose fundamentally different demands on the programmer. Programming in the large Large programs (e.g. operating systems, database systems, compilers, application packages) tax our organizational ability. The most important issues to be dealt with include requirements analysis, functional specification, compatibility with other systems, how to break a large program into modules of manageable size, documentation, adaptability to new systems and new requirements, how to organize the team of programmers, and how to test the software. These issues are the staple of software engineering. When compared to the daunting managerial and design challenges, the task of actual coding is relatively simple. Large programs are often flat: Most of the listing consists of comments, interface specifications, definitions, declarations, initializations, and a lot of code that is executed only rarely. Although the function of any single page of source code may be rather trivial when considered by itself, it is difficult to understand the entire program, as you need a lot of information to understand how this page relates to the whole. The classic book on programming in the large is [Bro 75]. Programming in the small Small programs, of the kind discussed in this book, challenge our technical know-how and inventiveness. Algorithmic issues dominate the programmer's thinking: Among several algorithms that all solve the same problem, which is the most efficient under the given circumstances? How much time and space does it take? What data structures do we use? In contrast to large programs, small programs are usually deep, consisting of short, compact code many of whose statements are executed very often. Understanding a small program may also be difficult, at least initially, since the chain of thought is often subtle. Once you understand it thoroughly, you can reproduce it at any time with much less effort than was first required. Mastery of interesting small programs is the Algorithms and Data Structures 34 A Global Text
algorithms and data structures_Page_34_Chunk4574
4. Algorithms and programs as literature: substance and form best way to get started in computer science. We encourage the reader to work out all the details of the examples we present. This book is concerned only with programming in the small. This decision determines our choice of topics to be presented, our style of presentation, and the notation we use to express programs, explanations, and proofs, and heavily influences our comments on techniques of programming. Our style of presentation appeals to the reader's intuition more than to formal rigor. We aim at highlighting the key idea of any argument that we make rather than belaboring the details. We take the liberty of using a free notation that suits the purpose of any specific argument we wish to make, trusting that the reader understands our small programs so well that he can translate them into the programming language of his choice. In a nut shell, we emphasize substance over form. The purpose of Part II is to help engender a fluency in using different notations. We provide yet other examples of unconventional notations that match the nature of the problem they are intended to describe, and we show how to translate them into Pascal-like programs. Since much of the difference between programming languages is merely syntactic, we include two chapters that cover the basics of syntax and syntax analysis. These topics are important in their own right; we present them early in the hope that they will help the student see through differences of notation that are merely "syntactic sugar". Documentation versus literature: is it meant to be read? It is instructive to distinguish two types of written materials, and two corresponding types of writing tasks: documents and literature. Documents are constrained by requirements of many kinds, are read when a specific need arises (rarely for pleasure), and their quality is judged by criteria such as formality, conformity to a standard, completeness, accuracy, and consistency. Literature is a form of art free from conventions, read for education or entertainment, and its quality is judged by aesthetic criteria much harder to enumerate than the ones above. The touchstone is the question: Is it meant to be read? If the answer is "only if necessary", then it's a document, not literature. As the name implies, the documentation of large programs is a typical document-writing chore. Much has been written in software engineering about documentation, a topic whose importance grows with the size and complexity of the system to be documented. We hold that small programs are not documented, they are explained. As such, they are literature, or ought to be. The idea of programs as literature is widely held (see, e.g. [Knu 84]). The key idea is that an algorithm or program is part of the text and melts into the text in the same way as a paragraph, a formula, or a picture does. There are also formal notations and systems designed to support a style of programming that integrates text and code to form a package that is both readable for humans and executable by machines [Knu 83]. Whatever notation is used for literate programming, it has to describe all phases of a program's evolution, from idea to specification to algorithm to program. Details of a good program cannot be understood, or at least not appreciated, without an awareness of the grand design that guided the programmer. Whereas details are usually well expressed in some formal notation, grand designs are not. For this reason we renounce formality and attempt to convey ideas in whatever notation suits our purpose of insightful explanation. Let us illustrate this philosophy with some examples. 35
algorithms and data structures_Page_35_Chunk4575
This book is licensed under a Creative Commons Attribution 3.0 License A snowflake Fractal pictures are intuitively characterized by the requirement that any part of the picture, of any size, when sufficiently magnified, looks like the whole picture. Two pieces of information are required to define a specific fractal: 1. A picture primitive that serves as a building-block: Many copies of this primitive, scaled to many different sizes, are composed to generate the picture. 2. A recursive rule that defines the relative position of the primitives of different size. A picture primitive is surely best defined by a drawing, and the manner of composing primitives in space again calls for a pictorial representation, perhaps augmented by a verbal explanation. In this style we define the fractal 'Snowflake' by the following production rule, which we read as follows: A line segment, as shown on the left-hand side, must be replaced by a polyline, a chain of four shorter segments, as shown at the right-hand side (Exhibit 4.1). We start with an initial configuration (the zero-generation) consisting of a single segment (Exhibit 4.2). If we apply the production rule just once to every segment of the current generation, we obtain successively a first, second, and third generation, as shown in Exhibit 4.3. Further generations quickly exhaust the resolution of a graphics screen or the printed page, so we stop drawing them. The curve obtained as the limit when this process is continued indefinitely is a fractal. Although we cannot draw it exactly, one can study it as a mathematical object and prove theorems about it. Exhibit 4.1: Production for replacing a straight-line segment by a polyline Exhibit 4.2: The simplest initial configuration Exhibit 4.3: The first three generations The production rule drawn above is the essence of this fractal, and of the sequence of pictures that lead up to it. The initial configuration, on the other hand, is quite arbitrary: If we had started with a regular hexagon, rather than a single line segment, the pictures obtained would really have lived up to their name, snowflake. Any other initial configuration still generates curves with the unmistakable pattern of snowflakes, as the reader is encouraged to verify. After having familiarized ourselves with the objects described, let us turn our attention to the method of description and raise three questions about the formality and executability of such notations. 1. Is our notation sufficiently formal to serve as a program for a computer to draw the family of generations of snowflakes? Certainly not, as we stated certain rules in colloquial language and left others completely unsaid, implying them only by sample drawings. As an example of the latter, consider the question: If a Algorithms and Data Structures 36 A Global Text
algorithms and data structures_Page_36_Chunk4576
4. Algorithms and programs as literature: substance and form segment is to be replaced by a "plain with a mountain in the center", on which side of the segment should the peak point? The drawings above suggest that all peaks stick out on the same side of the curve, the outside. 2. Could our method of description be extended and formalized to serve as a programming language for fractals? Of course. As an example, the production shown in Exhibit 4.4 specifies the side on which the peak is to point. Every segment now has a + side and a – side. The production above states that the new peak is to grow over the + side of the original segment and specifies the + sides and – sides of each of the four new segments. For every other aspect that our description may have left unspecified, such as placement on the screen, some notation could readily be designed to specify every detail with complete rigor. In “Syntax” and “Syntax analysis” we introduce some of the basic techniques for designing and using formal notations. Exhibit 4.4: Refining the description to specify a "left-right" orientation. 3. Should we formalize this method of description and turn it into a machine-executable notation? It depends on the purpose for which we plan to use it. Often in this book we present just one or a few examples that share a common design. Our goal is for the reader to understand these few examples, not to practice the design of artificial programming languages. To avoid being sidetracked by a pedantic insistence on rigorous notation, with its inevitable overhead of introducing formalisms needed to define all details, we prefer to stop when we have given enough information for an attentive reader to grasp the main idea of each example. Hilbert's space-filling curve Space-filling curves have been an object of mathematical curiosity since the nineteenth century, as they can be used to prove that the cardinality of an interval, considered as a set of points, equals the cardinality of a square (or any other finite two-dimensional region). The term space-filling describes the surprising fact that such a curve visits every point within a square. In mathematics, space-filling curves are constructed as the limit to which an infinite sequence of curves Ci converges. On a discretized plane, such as a raster-scanned screen, no limiting process is needed, and typically one of the first dozen curves in the sequence already paints every pixel, so the term space-filling is quickly seen to be appropriate. Let us illustrate this phenomenon using Hilbert's space-filling curve (David Hilbert, 1862–1943), whose first six approximations are shown in Exhibit 4.5. As the pictures suggest, Hilbert curves are best-described recursively, but the composition rule is more complicated than the one for snowflakes. We propose the two productions shown in Exhibit 4.6 to capture the essence of Hilbert (and similar) curves. This pictorial program requires explanation, but we hope the reader who has once understood it will find this notation useful for inventing fractals of her own. As always, a production is read: "To obtain an instance of the left-handside, get instances of all the things listed on the right-handside", or equivalently, "to do the task specified by the left-hand side, do all the tasks listed on the right- hand side". 37
algorithms and data structures_Page_37_Chunk4577
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 4.5: Six generations of the family of Hilbert curves Exhibit 4.6: Productions for painting a square in terms of its quadrants The left-hand side of the first production stands for the task: paint a square of given size, assuming that you enter at the lower left corner facing in the direction indicated by the arrow and must leave in the upper left corner, again facing in the direction indicated by that arrow. We assume turtle graphics primitives, where the state of the brush is given by a position and a direction. The hatching indicates the area to be painted. It lies to the right of the line that connects entry and exit corners, which we read as "paint with your right hand", and the hatching is in thick strokes. The left-hand side of the second production is similar: Paint a square "with your left hand" (hatching is in thin strokes), entering and exiting as indicated by the arrows. The right-hand sides of the productions are now easily explained. They say that in order to paint a square you must paint each of its quadrants, in the order indicated. They give explicit instructions on where to enter and exit, Algorithms and Data Structures 38 A Global Text
algorithms and data structures_Page_38_Chunk4578
4. Algorithms and programs as literature: substance and form what direction to face, and whether you are painting with your right or left hand. The last detail is to make sure that when the brush exits from one quadrant it gets into the correct state for entering the next. This requires the brush to turn by 90˚, either left or right, as the curved arrows in the pictures indicate. In the continuous plane we imagine the brush to "turn on its heels", whereas on a discrete grid it also moves to the first grid point of the adjacent quadrant. These productions omit any rule for termination, thus simulating the limiting process of true space-filling curves. To draw anything on the screen we need to add some termination rules that specify two things: (1) when to invoke the termination rule (e.g. at some fixed depth of recursion), and (2) how to paint the square that invokes the termination rule (e.g. paint it all black). As was the case with snowflakes and with all fractals, the primitive pictures are much less important than the composition rule, so we omit it. The following program implements a specific version of the two pictorial productions shown above. The procedure 'Walk' implements the curved arrows in the productions: the brush turns by 'halfTurn', takes a step of length s, and turns again by 'halfTurn'. The parameter 'halfTurn' is introduced to show the effect of cumulative small errors in recursive procedures. 'halfTurn = 45' causes the brush to make right-angle turns and yields Hilbert curves. The reader is encouraged to experiment with 'halfTurn = 43, 44, 46, 47', and other values. program PaintAndWalk; const pi = 3.14159; s = 3; { step size of walk } var turtleHeading: real; { counterclockwise, radians } halfTurn, depth: integer; { recursive depth of painting } procedure TurtleTurn(angle: real); { turn the turtle angle degrees counterclockwise } begin { angle is converted to radian before adding } turtleHeading := turtleHeading + angle · pi / 180.0 end; { TurtleTurn } procedure TurtleLine(dist: real); { draws a straight line, dist units long } begin Line(round(dist · cos(turtleHeading)), round(–dist·sin(turtle Heading))) end; { TurtleLine } procedure Walk (halfTurn: integer); begin TurtleTurn(halfTurn); TurtleLine(s); TurtleTurn(halfTurn) end; procedure Qpaint (level: integer; halfTurn: integer); begin if level = 0 then TurtleTurn(2 · halfTurn) else begin Qpaint(level – 1, –halfTurn); Walk(halfTurn); Qpaint(level – 1, halfTurn); Walk(–halfTurn); Qpaint(level – 1, halfTurn); Walk(halfTurn); Qpaint(level – 1, –halfTurn) end end; { Qpaint } begin { PaintAndWalk } 39
algorithms and data structures_Page_39_Chunk4579
This book is licensed under a Creative Commons Attribution 3.0 License ShowText; ShowDrawing; MoveTo(100, 100); turtleHeading := 0; { initialize turtle state } WriteLn('Enter halfTurn 0 .. 359 (45 for Hilbert curves): '); ReadLn(halfTurn); TurtleTurn(–halfTurn); { init turtle turning angle } Write('Enter depth 1 .. 6: '); ReadLn(depth); Qpaint(depth, halfTurn) end. { PaintAndWalk } As a summary of this discourse on notation, we point to the fact that an executable program necessarily has to specify many details that are irrelevant from the point of view of human understanding. This book assumes that the reader has learned the basic steps of programming, of thinking up such details, and being able to express them formally in a programming language. Compare the verbosity of the one-page program above with the clarity and conciseness of the two pictorial productions above. The latter state the essentials of the recursive construction, and no more, in a manner that a human can understand "at a glance". We aim our notation to appeal to a human mind, not necessarily to a computer, and choose our notation accordingly. Pascal and its dialects: lingua franca of computer science Lingua franca (1619): 1. A common language that consists of Italian mixed with French, Spanish, Greek and Arabic and is spoken in Mediterranean ports 2. Any of various languages used as common or commercial tongues among peoples of diverse speech 3. Something resembling a common language (From Webster's Collegiate Dictionary) Pascal as representative of today's programming languages The definition above fits Pascal well: In the mainstream of the development of programming languages for a couple of decades, Pascal embodies, in a simple design, some of the most important language features that became commonly accepted in the 1970s. This simplicity, combined with Pascal's preference for language features that are now well understood, makes Pascal a widely understood programming notation. A few highlights in the development of programming languages may explain how Pascal got to be a lingua franca of computer science. Fortran emerged in 1954 as the first high-level programming language to gain acceptance and became the programming language of the 1950s and early 1960s. Its appearance generated great activity in language design, and suddenly, around 1960, dozens of programming languages emerged. Three among these, Algol 60, COBOL, and Lisp, became milestones in the development of programming languages, each in its own way. Whereas COBOL became the most widely used language of the 1960s and 1970s, and Lisp perhaps the most innovative, Algol 60 became the most influential in several respects: it set new standards of rigor for the definition and description of a language, it pioneered hierarchical block structure as the major technique for organizing large programs, and through these major technical contributions became the first of a family of mainstream programming languages that includes PL/1, Algol 68, Pascal, Modula-2, and Ada. The decade of the 1960s remained one of great ferment and productivity in the field of programming languages. PL/1 and Algol 68, two ambitious projects that attempted to integrate many recent advances in programming language technology and theory, captured the lion's share of attention for several years. Pascal, a much smaller Algorithms and Data Structures 40 A Global Text
algorithms and data structures_Page_40_Chunk4580
4. Algorithms and programs as literature: substance and form project and language designed by Niklaus Wirth during the 1960s, ended up eclipsing both of these major efforts. Pascal took the best of Algol 60, in streamlined form, and added just one major extension, the then novel type definitions [Hoa 72]. This lightweight edifice made it possible to implement efficient Pascal compilers on the microcomputers that mushroomed during the mid 1970s (e.g. UCSD Pascal), which opened the doors to universities and high schools. Thus Pascal became the programming language most widely used in introductory computer science education, and every computer science student must be fluent in it. Because Pascal is so widely understood, we base our programming notation on it but do not adhere to it slavishly. Pascal is more than 20 years old, and many of its key ideas are 30 years old. With today's insights into programming languages, many details would probably be chosen differently. Indeed, there are many "dialects" of Pascal, which typically extend the standard defined in 1969 [Wir 71] in different directions. One extension relevant for a publication language is that with today's hardware that supports large character sets and many different fonts and styles, a greater variety of symbols can be used to make the source more readable. The following examples introduce some of the conventions that we use often. "Syntactic sugar": the look of programming notations Pascal statements lack an explicit terminator. This makes the frequent use of begin-end brackets necessary, as in the following program fragment, which implements the insertion sort algorithm (see chapter 17 and the section "Simple sorting algorithms that work in time"); –∞ denotes a constant ≤ any key value: A[0] := –∞; for i := 2 to n do begin j := i; while A[j] < A[j – 1] do begin t := A[j]; A[j] := A[j – 1]; A[j – 1] := t; j := j – 1 end; end; We aim at brevity and readability but wish to retain the flavor of Pascal to the extent that any new notation we introduce can be translated routinely into standard Pascal. Thus we write the statements above as follows: A[0] := –∞; for i := 2 to n do begin j := i; { comments appear in italics } while A[j] < A[j – 1] do { A[j] :=: A[j – 1]; j := j – 1 } { braces serve as general-purpose brackets, including begin-end } { :=: denotes the exchange operator } end; Borrowing heavily from standard mathematical notation, we use conventional mathematical signs to denote operators whose Pascal designation was constrained by the small character sets typical of the early days, such as: ≠ ≤ ≥ ≠ ¬ ∧ ∨ ∈ ∉ ∩ ∪\ |x| instead of <> <= >= <> not and or in not in · + – abs(x) respectively We also use signs that may have no direct counterpart in Pascal, such as: ⊃ ⊇ ⊄ ⊂ ⊆ Set-theoretic relations ∞ Infinity, often used for a "sentinel" (i.e. a number larger than all numbers to be processed in a given 41
algorithms and data structures_Page_41_Chunk4581
This book is licensed under a Creative Commons Attribution 3.0 License application) ± Plus-or-minus, used to define an interval [of uncertainty] ∑∏ Sum and product x Ceiling of a real number x (i.e. the smallest integer ≥ x) x Floor of a real number x (i.e. the largest integer ≤ x) √ Square root log Logarithm to the base 2 ln Natural logarithm, to the base e iff If and only if Although we may take a cavalier attitude toward notational differences, and readily use concise notations such as ∧ ∨ for the more verbose 'and', 'or', we will try to remind readers explicitly about our assumptions when there is a question about semantics. As an example, we assume that the boolean operators ∧ and ∨ are conditional, also called 'cand' and 'cor': An expression containing these operators is evaluated from left to right, and the evaluation stops as soon as the result is known. In the expression x ∧ y, for example, x is evaluated first. If x evaluates to 'false', the entire expression is 'false' without y ever being evaluated. This convention makes it possible to leave y undefined when x is 'false'. Only if x evaluates to 'true' do we proceed to evaluate y. An analogous convention applies to x ∨ y. Program structure Whereas the concise notations introduced above to denote operators can be translated almost one-to-one into a single line of standard Pascal, we also introduce a few extensions that may affect the program structure. In our view these changes make programs more elegant and easier to understand. Borrowing from many modern languages, we introduce a 'return()' statement to exit from procedures and functions and to return the value computed by a function. Example function gcd(u, v: integer): integer; { computes the greatest common divisor (gcd) of u and v } begin if v = 0 then return(u) else return(gcd(v, u mod v)) end; In this example, 'return()' merely replaces the Pascal assignments 'gcd := u' and 'gcd := gcd(v, u mod v)'. The latter in particular illustrates how 'return()' avoids a notational blemish in Pascal: On the left of the second assignment, 'gcd' denotes a variable, on the right a function. 'Return()' also has the more drastic consequence that it causes control to exit from the surrounding procedure or function as soon as it is executed. Without entering into a controversy over the general advantages and disadvantages of this "flow of control" mechanism, let us present one example, typical of many search procedures, where 'return()' greatly simplifies coding. The point is that a search Algorithms and Data Structures 42 A Global Text
algorithms and data structures_Page_42_Chunk4582
4. Algorithms and programs as literature: substance and form routine terminates in one of (at least) two different ways: successfully, by having found the item in question, or unsuccessfully, because of a number of reasons (the item is not present, and some index is about to fall outside the range of a table; we cannot insert an item because the table is full, or we cannot pop a stack because it is empty, etc.). For the sake of efficiency as well as readability we prefer to exit from the routine as soon as a case has been identified and dealt with, as the following example from “Address computation:” illustrates: function insert-into-hash-table(x: key): addr; var a: addr; begin a := h(x); { locate the home address of the item x to be inserted } while T[a] ≠ empty do begin { skipping over cells that are already occupied } if T[a] = x then return(a); { x is already present; return its address } a := (a + 1) mod m { keep searching at the next address } end; { we've found an empty cell; see if there is room for x to be inserted } if n < m – 1 then { n := n + 1; T[a] := x } else err- msg('table is full'); return(a) { return the address where x was inserted } end; This code can only be appreciated by comparing it with alternatives that avoid the use of 'return()'. We encourage readers to try their hands at this challenge. Notice the three different ways this procedure can terminate: (1) no need to insert x because x is already in the table, (2) impossible to insert x because the table is full, and (3) the normal case when x is inserted. Standard Pascal incorporates no facilities for "exception handling" (e.g. to cover the first two cases that should occur only rarely) and forces all three outcomes to exit the procedure at its textual end. Let us just mention a few other liberties that we may take. Whereas Pascal limits results of functions to certain simple types, we will let them be of any type: in particular, structured types, such as records and arrays. Rather than nesting if-then-else statements in order to discriminate among more than two mutually exclusive cases, we use the "flat" and more legible control structure: if B1 then S1 elsif B2 then S2 elsif … else Sn ; Our sample programs do not return dynamically allocated storage explicitly. They rely on a memory management system that retrieves free storage through "garbage collection". Many implementations of Pascal avoid garbage collection and instead provide a procedure 'dispose(…)' for the programmer to explicitly return unneeded cells. If you work with such a version of Pascal and write list-processing programs that use significant amounts of memory, you must insert calls to 'dispose(…)' in appropriate places in your programs. The list above is not intended to be exhaustive, and neither do we argue that the constructs we use are necessarily superior to others commonly available. Our reason for extending the notation of Pascal (or any other programming language we might have chosen as a starting point) is the following: in addressing human readers, we believe an open-ended, somewhat informal notation is preferable to the straightjacket of any one programming language. The latter becomes necessary if and when we execute a program, but during the incubation period when 43
algorithms and data structures_Page_43_Chunk4583
This book is licensed under a Creative Commons Attribution 3.0 License our understanding slowly grows toward a firm grasp of an idea, supporting intuition is much more important than formality. Thus we describe data structures and algorithms with the help of figures, words, and programs as we see fit in any particular instance. Programming project 1. Use your graphics frame program of “Graphics primitives and environments” to implement an editor for simple graphics productions such as those used to define snowflakes (e.g. 'any line segment gets replaced by a specified sequence of line segments'), and an interpreter that draws successive generations of the fractals defined by these productions. Algorithms and Data Structures 44 A Global Text
algorithms and data structures_Page_44_Chunk4584
This book is licensed under a Creative Commons Attribution 3.0 License 5. Divide-and-conquer and recursion Learning objectives: • The algorithmic principle of divide-and-conquer leads directly to recursive procedures. • Examples: Merge sort, tree traversal. Recursion and iteration. • My friend liked to claim "I'm 2/3 Cherokee." Until someone would challenge him "Two- thirds? You mean 1/2 , or, or maybe 3/8, how on earth can you be 2/3 of anything?" "It's easy," said Jim, "both my parents are 2/3." An algorithmic principle Let A(D) denote the application of an algorithm A to a set of data D, producing a result R. An important class of algorithms, of a type called divide-and-conquer, processes data in two distinct ways, according to whether the data is small or large: • If the set D is small, and/or of simple structure, we invoke a simple algorithm A 0 whose application A0(D) yields R. • If the set D is large, and/or of complex structure, we partition it into smaller subsets D 1, … , Dk. For each i, apply A(Di) to yield a result Ri. Combine the results R1, … , Rk to yield R. This algorithmic principle of divide-and-conquer leads naturally to the notion of recursive procedures. The following example outlines the concept in a high-level notation, highlighting the role of parameters and local variables. procedure A(D: data; var R: result); var D1, … , Dk: data; R1, … , Rk: result; begin if simple(D) then R := A0(D) else { D1, … , Dk := partition(D); R1 := A(D1); … ; Rk := A(Dk); R := combine(R1, … , Rk) } end; Notice how an initial data set D spawns sets D1, … , Dk which, in turn, spawn children of their own. Thus the collection of all data sets generated by the partitioning scheme is a tree with root D. In order for the recursive procedure A(D) to terminate in all cases, the partitioning function must meet the following condition: Each branch of the partitioning tree, starting from the root D, eventually terminates with a data set D0 that satisfies the predicate 'simple(D0)', to which we can apply the algorithm. Divide-and-conquer reduces a problem on data set D to k instances of the same problem on new sets D 1, … , Dk that are "simpler" than the original set D. Simpler often means "has fewer elements", but any measure of Algorithms and Data Structures 45 A Global Text
algorithms and data structures_Page_45_Chunk4585
5. Divide-and-conquer and recursion "simplicity" that monotonically heads for the predicate 'simple' will do, when algorithm A0 will finish the job. "D is simple" may mean "D has no elements", in which case A0 may have to do nothing at all; or it may mean "D has exactly one element", and A0 may just mark this element as having been visited. The following sections show examples of divide-and-conquer algorithms. As we will see, the actual workload is sometimes distributed unequally among different parts of the algorithm. In the sorting example, the step 'R:=combine(R1, … , Rk)' requires most of the work; in the "Tower of Hanoi" problem, the application of algorithm A0 takes the most effort. Divide-and-conquer expressed as a diagram: merge sort Suppose that we wish to sort a sequence of names alphabetically, as shown in Exhibit 5.1. We make use of the divide-and-conquer strategy by partitioning a "large" sequence D into two subsequences D1 and D2, sorting each subsequence, and then merging them back together into sorted order. This is our algorithm A(D). If D contains at most one element, we do nothing at all. A0 is the identity algorithm, A0(D) = D. Exhibit 5.1: Sorting the sequence {Z, A, S, D} by using a divide-and-conquer scheme procedure sort(var D: sequence); var D1, D2: sequence; function combine(D1, D2: sequence): sequence; begin { combine } merge the two sorted sequences D1 and D2 into a single sorted sequence D'; return(D') end; { combine } begin { sort} if |D| > 1 then { split D into two sequences D1 and D2 of equal size; sort(D1); sort(D2); D := combine(D1, D2) } { if |D| ≤ 1, D is trivially sorted, do nothing } end; { sort } 46
algorithms and data structures_Page_46_Chunk4586
This book is licensed under a Creative Commons Attribution 3.0 License In the chapter on “sorting and its complexity”, under the section “merging and merge sorts” we turn this divide- and-conquer scheme into a program. Recursively defined trees A tree, more precisely, a rooted, ordered tree, is a data type used primarily to model any type of hierarchical organization. Its primitive parts are nodes and leaves. It has a distinguished node called the root, which, in violation of nature, is typically drawn at the top of the page, with the tree growing downward. Each node has a certain number of children, either leaves or nodes; leaves have no children. The exact definition of such trees can differ slightly with respect to details and terminology. We may define a binary tree, for example, by the condition that each node has either exactly, or at most, two children. The pictorial grammar shown in Exhibit 5.2 captures this recursive definition of 'binary tree' and fixes the details left unspecified by the verbal description above. It uses an alphabet of three symbols: the nonterminal 'tree symbol', which is also the start symbol; and two terminal symbols, for 'node' and for 'leaf'. Exhibit 5.2: The three symbols of the alphabet of a tree grammar There are two production or rewriting rules, p1 and p2 (Exhibit 5.3). The derivation shown in Exhibit 5.4 illustrates the application of the production rules to generate a tree from the nonterminal start symbol. Exhibit 5.3: Rule p1 generates a leaf, rule p2 generates a node and two new trees Exhibit 5.4: One way to derive the tree at right We may make the production rules more detailed by explicitly naming the coordinates associated with each symbol. On a display device such as a computer screen, the x- and y-values of a point are typically Cartesian coordinates with the origin in the upper-left corner. The x-values increase toward the bottom and the y-values increase toward the right of the display. Let (x, y) denote the screen position associated with a particular symbol, and let d denote the depth of a node in the tree. The root has depth 0, and the children of a node with depth d have depth d+1. The different levels of the tree are separated by some constant distance s. The separation between siblings is determined by a (rapidly decreasing) function t(d) which takes as argument the depth of the siblings and depends on the drawing size of the symbols and the resolution of the screen. These more detailed productions are shown in Exhibit 5.5. Algorithms and Data Structures 47 A Global Text
algorithms and data structures_Page_47_Chunk4587
5. Divide-and-conquer and recursion Exhibit 5.5: Adding coordinate information to productions in order to control graphic layout The translation of these two rules into high-level code is now plain: procedure p1(x, y: coordinate); begin eraseTreeSymbol(x, y); drawLeafSymbol(x, y) end; procedure p2(x, y: coordinate; d: level); begin eraseTreeSymbol(x, y); drawNodeSymbol(x, y); drawTreeSymbol(x + s, y – t(d + 1)); drawTreeSymbol(x + s, y + t(d + 1)) end; If we choose t(d) = c · 2–d, these two procedures produce the display shown in Exhibit 5.6 of the tree generated in Exhibit 5.4. Exhibit 5.6: Sample layout obtained by halving horizontal displacement at each successive level Technical remark about the details of defining binary trees: Our grammar forces every node to have exactly two children: A child may be a node or a leaf. This lets us subsume two frequently occurring classes of binary trees under one common definition. 1. 0-2 (binary) trees. We may identify leaves and nodes, making no distinction between them (replace the squares by circles in Exhibit 5.3 and Exhibit 5.4). Every node in the new tree now has either zero or two children, but not one. The smallest tree has a single node, the root. 2. (Arbitrary) Binary trees. Ignore the leaves (drop the squares in Exhibit 5.3 and Exhibit 5.4 and the branches leading into a square). Every node in the new tree now has either zero, one, or two children. The smallest tree (which consisted of a single leaf) now has no node at all; it is empty. For clarity's sake, the following examples use the terminology of nodes and leaves introduced in the defining grammar. In some instances we point out what happens under the interpretation that leaves are dropped. 48
algorithms and data structures_Page_48_Chunk4588
This book is licensed under a Creative Commons Attribution 3.0 License Recursive tree traversal Recursion is a powerful tool for programming divide-and-conquer algorithms in a straightforward manner. In particular, when the data to be processed is defined recursively, a recursive processing algorithm that mirrors the structure of the data is most natural. The recursive tree traversal procedure below illustrates this point. Traversing a tree (in general: a graph, a data structure) means visiting every node and every leaf in an orderly sequence, beginning and ending at the root. What needs to be done at each node and each leaf is of no concern to the traversal algorithm, so we merely designate that by a call to a 'procedure visit( )'. You may think of inspecting the contents of all nodes and/or leaves, and writing them to a file. Recursive tree traversals use divide-and-conquer to decompose a tree into its subtrees: At each node visited along the way, the two subtrees L and R to the left and right of this node must be traversed. There are three natural ways to sequence the node visit and the subtree traversals: 1. node; L; R { preorder, or prefix } 2. L; node; R { inorder or infix } 3. L; R; node { postorder or suffix } The following example translates this traversal algorithm into a recursive procedure: procedure traverse(T: tree); { preorder, inorder, or postorder traversal of tree T with leaves } begin if leaf(T) then visitleaf(T) else { T is composite } { visit1(root(T)); traverse(leftsubtree(T)); visit2(root(T)); traverse(rightsubtree(T); visit3(root(T)) } end; When leaves are ignored (i.e. a tree consisting of a single leaf is considered to be empty), the procedure body becomes slightly simpler: if not empty(T) then { … } To accomplish the k-th traversal scheme (k = 1, 2, 3), 'visitk' performs the desired operation on the node, while the other two visits do nothing. If all three visits print out the name of the node, we obtain a sequence of node names called 'triple tree traversal', shown in Exhibit 5.7 along with the three traversal orders of which it is composed. During the traversal the nodes are visited in the following sequence: Algorithms and Data Structures 49 A Global Text
algorithms and data structures_Page_49_Chunk4589
5. Divide-and-conquer and recursion Exhibit 5.7: Three standard orders merged into a triple tree traversal Recursion versus iteration: the Tower of Hanoi The "Tower of Hanoi" is a stack of n disks of different sizes, held in place by a tall peg (Exhibit 5.8). The task is to transfer the tower from source peg S to a target peg T via an intermediate peg I, one disk at a time, without ever placing a larger disk on a smaller one. In this case the data set D is a tower of n disks, and the divide-and-conquer algorithm A partitions D asymmetrically into a small "tower" consisting of a single disk (the largest, at the bottom of the pile) and another tower D' (usually larger, but conceivably empty) consisting of the n – 1 topmost disks. The puzzle is solved recursively in three steps: 1. Transfer D' to the intermediate peg I. 2. Move the largest disk to the target peg T. 3. Transfer D' on top of the largest disk at the target peg T. Exhibit 5.8: Initial configuration of the Tower of Hanoi. Step 1 deserves more explanation. How do we transfer the n – 1 topmost disks from one peg to another? Notice that they themselves constitute a tower, to which we may apply the same three-step algorithm. Thus we are presented with successively simpler problems to solve, namely, transferring the n – 1 topmost disks from one peg to another, for decreasing n, until finally, for n = 0, we do nothing. procedure Hanoi(n: integer; x, y, z: peg); { transfer a tower with n disks from peg x, via y, to z } begin if n > 0 then { Hanoi(n – 1, x, z, y); move(x, z); Hanoi(n – 1, y, x, z) } end; Recursion has the advantage of intuitive clarity. Elegant and efficient as this solution may be, there is some complexity hidden in the bookkeeping implied by recursion. 50
algorithms and data structures_Page_50_Chunk4590
This book is licensed under a Creative Commons Attribution 3.0 License The following procedure is an equally elegant and more efficient iterative solution to this problem. It assumes that the pegs are cyclically ordered, and the target peg where the disks will first come to rest depends on this order and on the parity of n (Exhibit 5.9). For odd values of n, 'IterativeHanoi' moves the tower to peg I, for even values of n, to peg T. Exhibit 5.9: Cyclic order of the pegs. procedure IterativeHanoi(n: integer); var odd: boolean; { odd represents the parity of the move } begin odd := true; repeat case odd of true: transfer smallest disk cyclically to next peg; false: make the only legal move leaving the smallest in place end; odd := not odd until entire tower is on target peg end; Exercise: recursive or iterative pictures? Chapter 4 presented some beautiful examples of recursive pictures, which would be hard to program without recursion. But for simple recursive pictures iteration is just as natural. Specify a convenient set of graphics primitives and use them to write an iterative procedure to draw Exhibit 5.10 to a nesting depth given by a parameter d. Exhibit 5.10: Interleaved circles and equilateral triangles cause the radius to be exactly halved at each step. Solution There are many choices of suitable primitives and many ways to program these pictures. Specifying an equilateral triangle by its center and the radius of its circumscribed circle simplifies the notation. Assume that we may use the procedures: procedure circle(x, y, r: real); { coordinates of center and radius } procedure equitr(x, y, r: real); { center and radius of circumscribed circle} Algorithms and Data Structures 51 A Global Text
algorithms and data structures_Page_51_Chunk4591
5. Divide-and-conquer and recursion procedure citr(x, y, r: real; d: integer); var vr: real; { variable radius } i: integer; begin vr := r; for i := 1 to d do { equitr(x, y, vr); vr := vr/2; circle(x, y, vr) } { show that the radius of consecutively nested circles gets exactly halved at each step } end; The flag of Alfanumerica: an algorithmic novel on iteration and recursion In the process of automating its flag industry, the United States of Alfanumerica announced a competition for the most elegant program to print its flag: All solutions submitted to the prize committee fell into one of two classes, the iterative and recursive programs. The proponents of these two algorithm design principles could not agree on a winner, and the selection process sparked a civil war that split the nation into two: the Iterative States of Alfanumerica (ISA) and the Recursive States of Alfanumerica (RSA). Both nations fly the same flag but use entirely different production algorithms. 1. Write a procedure ISA(k: integer); to print the ISA flag, using an iterative algorithm, of course. Assume that k is a power of 2 and k ≤ (half the line length of the printer). 2. Explain why the printer industry in RSA is much more innovative than the one in ISA. All modern RSA printers include operations for positioning the writing head anywhere within a line, and line feed works both forward and backward. 3. Specify the precise operations for some RSA printer of your design. Using these operations, write a recursive procedure RSA(k: integer); to print the RSA flag. 4. Explain an unforeseen consequence of this drive to automate the flag industry of Alfanumerica: In both ISA and RSA, a growing number of flags can be seen fluttering in the breeze turned around by 90˚. Exercises 1. Whereas divide-and-conquer algorithms usually attempt to divide the data in equal halves, the recursive Tower of Hanoi procedure presented in the section 'Recursion versus iteration: The Tower of Hanoi" divides the data in a very asymmetric manner: a single disk versus n – 1 disks. Why? 2. Prove by induction on n that the iterative program 'IterativeHanoi' solves the problem in 2n–1 iterations. 52 **************** ******** ******** **** **** **** **** ** ** ** ** ** ** ** ** * * * * * * * * * * * * * * * * k blanks followed by k stars twice (k/2 blanks followed by k/2 stars) … continue doubling and halving down to runs length of 1.
algorithms and data structures_Page_52_Chunk4592
This book is licensed under a Creative Commons Attribution 3.0 License 6. Syntax Learning objectives: • syntax and semantics • syntax diagrams and EBNF describe context-free grammars • terminal and nonterminal symbols • productions • definition of EBNF by itself • parse tree • grammars must avoid ambiguities • infix, prefix, and postfix notation for arithmetic expressions • prefix and postfix notation do not need parentheses Syntax and semantics Computer science has borrowed some important concepts from the study of natural languages (e.g. the notions of syntax and semantics). Syntax rules prescribe how the sentences of a language are formed, independently of their meaning. Semantics deals with their meaning. The two sentences "The child draws the horse" and "The horse draws the child" are both syntactically correct according to the accepted rules of grammar. The first sentence clearly makes sense, whereas the second sentence is baffling: perhaps senseless (if "draw" means "drawing a picture"), perhaps meaningful (if "draw" means "pull"). Semantic aspects—whether a sentence is meaningful or not, and if so, what it means—are much more difficult to formalize and decide than syntactic issues. However, the analogy between natural languages and programming languages does not go very far. The choice of English words and phrases such as "begin", "end", "goto", "if-then-else" lends a programming language a superficial similarity to natural language, but no more. The possibility of verbal encoding of mathematical formulas into pseudo-English has deliberately been built into COBOL; for example, "compute velocity times time giving distance" is nothing but syntactic sugar for "distance := velocity · time". Much more important is the distinction that natural languages are not rigorously defined (neither the vocabulary, nor the syntax, and certainly not the semantics), whereas programming languages should be defined according to a rigorous formalism. Programming languages are much closer to the formal notations of mathematics than to natural languages, and programming notation would be a more accurate term. The lexical part of a modern programming language [the alphabet, the set of reserved words, the construction rules for the identifiers (i.e. the equivalent to the vocabulary of a natural language) and the syntax are usually defined formally. However, system-dependent differences are not always described precisely. The compiler often determines in detail the syntactic correctness of a program with respect to a certain system (computer and operating system). The semantics of a programming language could also be defined formally, but this is rarely done, because formal semantic definitions are extensive and difficult to read. Algorithms and Data Structures 53 A Global Text
algorithms and data structures_Page_53_Chunk4593
6. Syntax The syntax of a programming language is not as important as the semantics, but good understanding of the syntax often helps in understanding the language. With some practice one can often guess the semantics from the syntax, since the syntax of a well-designed programming language is the frame that supports the semantics. Grammars and their representation: syntax diagrams and EBNF The syntax of modern programming languages is defined by grammars. These are mostly of a type called context-free grammars, or close variants thereof, and can be given in different notations. Backus-Naur form (BNF), a milestone in the development of programming languages, was introduced in 1960 to define the syntax of Algol. It is the basis for other notations used today, such as EBNF (extended BNF) and graphical representations such as syntax diagrams. EBNF and syntax diagrams are syntactic notations that describe exactly the context-free grammars of formal language theory. Recursion is a central theme of all these notations: the syntactic correctness and structure of a large program text are reduced to the syntactic correctness and structure of its textual components. Other common notions include: terminal symbol, nonterminal symbol, and productions or rewriting rules that describe how nonterminal symbols generate strings of symbols. The set of terminal symbols forms the alphabet of a language, the symbols from which the sentences are built. In EBNF a terminal symbol is enclosed in single quotation marks; in syntax diagrams a terminal symbol is represented by writing it in an oval: Nonterminal symbols represent syntactic entities: statements, declarations, or expressions. Each nonterminal symbol is given a name consisting of a sequence of letters and digits, where the first character must be a letter. In syntax diagrams a nonterminal symbol is represented by writing its name in a rectangular box: If a construct consists of the catenation of constructs A and B, this is expressed by If a construct consists of either A or B, this is denoted by If a construct may be either construct A or nothing, this is expressed by If a construct consists of the catenation of any number of A's (including none), this is denoted by In EBNF parentheses may be used to group entities [e.g. ( A | B )]. 54
algorithms and data structures_Page_54_Chunk4594
This book is licensed under a Creative Commons Attribution 3.0 License For each nonterminal symbol there must be at least one production that describes how this syntactic entity is formed from other terminal or nonterminal symbols using the composition constructs above: The following examples show productions and the constructs they generate. A, B, C, D may denote terminal or nonterminal symbols. EBNF is a formal language over a finite alphabet of symbols introduced above, built according to the rules explained above. Thus it is no great surprise that EBNF can be used to define itself. We use the following names for syntactic entities: stmt A syntactic equation. expr A list of alternative terms. term A concatenation of factors. factor A single syntactic entity or parenthesized expression. nts Nonterminal symbol that denotes a syntactic entity. It consists of a sequence of letters and digits where the first character must be a letter. ts Terminal symbol that belongs to the defined language's vocabulary. Since the vocabulary depends on the language to be defined there is no production for ts. EBNF is now defined by the following productions: EBNF = { stmt } . Algorithms and Data Structures 55 A Global Text
algorithms and data structures_Page_55_Chunk4595
6. Syntax stmt = nts '=' expr '.' . expr = term { '|' term } . term = factor { factor } . factor = nts | ts | '(' expr ')' | '[' expr ']' | '{' expr '}' . nts= letter { letter | digit } . Example: syntax of simple expressions The following productions for the three nonterminals E(xpression), T(erm), and F(actor) can be traced back to Algol 60. They form the core of all grammars for arithmetic expressions. We have simplified this grammar to define a class of expressions that lacks, for example, a unary minus operator and many other convenient notations. These details are but not important for our purpose: namely, understanding how this grammar assigns the correct structure to each expression. We have further simplified the grammar so that constants and variables are replaced by the single terminal symbol # (Exhibit 6.1): E = T { ( '+' | '–' ) T } . T = F { ( '·' | '/' ) F } . F = '#' | '(' E ')' . Exhibit 6.1: Syntax diagrams for simple arithmetic expressions. From the nonterminal E we can derive different expressions. In the opposite direction we start with a sequence of terminal symbols and check by syntactic analysis, or parsing, whether a given sequence is a valid expression. If this is the case the grammar assigns to this expression a unique tree structure, the parse tree (Exhibit 6.2). 56
algorithms and data structures_Page_56_Chunk4596
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 6.2: Parse tree for the expression # · ( # ) + # / # . Exercise: syntax diagrams for palindromes A palindrome is a string that reads the same when read forward or backward. Examples: 0110 and 01010. 01 is not a palindrome, as it differs from its reverse 10. 1. What is the shortest palindrome? 2. Specify the syntax of palindromes over the alphabet {0, 1} in EBNF-notation, and by drawing syntax diagrams. Solution 1. The shortest palindrome is the null or empty string. 2. S = [ '0' | '1' ] | '0' S '0' | '1' S '1' (Exhibit 6.3). Exhibit 6.3: Syntax diagram for palindromes An overly simple syntax for simple expressions Why does the grammar given in previous section contain term and factor? An expression E that involves only binary operators (e.g. +, –, · and /) is either a primitive operand, abbreviated as #, or of the form 'E op E'. Consider a "simpler" grammar for simple, parenthesis-free expressions (Exhibit 6.4): E = '#' | E ( '+' | '–' | '·' | '/' ) E . Algorithms and Data Structures 57 A Global Text
algorithms and data structures_Page_57_Chunk4597
6. Syntax Exhibit 6.4: A syntax that generates parse trees of ambiguous structure Now the expression # · # + # can be derived from E in two different ways (Exhibit 6.5). Such an ambiguous grammar is useless since we want to derive the semantic interpretation from the syntactic structure, and the tree at the left contradicts the conventional operator precedence of · over +. Exhibit 6.5: Two incompatible structures for the expression # · # + # . “Everything should be explained as simply as possible, but not simpler.” (Albert Einstein) We can salvage the idea of a grammar with a single nonterminal E by enclosing every expression of the form 'E op E' in parentheses, thus ensuring that every expression has a unique structure (Exhibit 6.6): E = '#' | '(' E ( '+' | '–' | '·' | '/' ) E ')' . Exhibit 6.6: Parentheses serve to restore unique structure. 58
algorithms and data structures_Page_58_Chunk4598
This book is licensed under a Creative Commons Attribution 3.0 License In doing so we change the language. The more complex grammar with three nonterminals E(xpression, T(erm), and F(actor) lets us write expressions that are only partially parenthesized and assigns to them a unique structure compatible with our priority conventions: · and / have higher priority than + and –. Exercise: the ambiguity of the dangling "else" The problem of the dangling "else" is an example of a syntax chosen to be "too simple" for the task it is supposed to handle. The syntax of several programming languages (e.g., Pascal) assigns to nested 'if-then[-else]' statements an ambiguous structure. It is left to the semantics of the language to disambiguate. Let E, E1, E2, … denote Boolean expressions, S, S1, S2, … statements. Pascal syntax allows two types of if statements: if E then S and if E then S else S 1. Draw one syntax diagram that expresses both of these syntactic possibilities. 2. Show all the possible syntactic structures of the statement if E1 then if E2 then S1 else S2 3. Propose a small modification to the Pascal language that avoids the syntactic ambiguity of the dangling else. Show that in your modified Pascal any arbitrarily nested structure of 'if-then' and 'if-then-else' statements must have a unique syntactic structure. Parenthesis-free notation for arithmetic expressions In the usual infix notation for arithmetic expressions a binary operator is written between its two operands. Even with operator precedence conventions, some parentheses are required to guarantee a unique syntactic structure. The selective use of parentheses complicates the syntax of infix expressions: Syntax analysis, interpretative evaluation, and code generation all become more complicated. Parenthesis-free or Polish notation (named for the Polish logician Jan Lukasiewicz) is a simpler notation for arithmetic expressions. All operators are systematically written either before (prefix notation) or after (postfix or suffix notation) the operands to which they apply. We restrict our examples to the binary operators +, –, · and /. Operators with different arities (i.e. different numbers of arguments) are easily handled provided that the number of arguments used is uniquely determined by the operator symbol. To introduce the unary minus we simply need a different symbol than for the binary minus. Infix a+b a+(b·c)(a+b)·c Prefix +ab +a·bc ·+abc Postfix ab+ abc·+ ab+c· Postfix notation mirrors the sequence of operations performed during the evaluation of an expression. 'ab+' is interpreted as: load a (find first operand); load b (find the second operand); add both. The syntax of arithmetic expressions in postfix notation is determined by the following grammar: S = '#' | S S ( '+' | '–' | '·' | '/' ) Algorithms and Data Structures 59 A Global Text
algorithms and data structures_Page_59_Chunk4599
6. Syntax Exhibit 6.7: Suffix expressions have a unique structure even without the use of parentheses. Exercises 1. Consider the following syntax, given in EBNF: S = A. A = B | 'IF' A 'THEN' A 'ELSE' A. B = C | B 'OR' C. C = D | C 'AND' D. D = 'x' | '(' A ')' | 'NOT' D. (a) Determine the sets of terminal and nonterminal symbols. (b) Give the syntax diagrams corresponding to the rules above. (c) Which of the following expressions is correct corresponding to the given syntax? For the correct expressions show how they can be derived from the given rules: x AND x x NOT AND x (x OR x) AND NOT x IF x AND x THEN x OR x ELSE NOT x x AND OR x 2. Extend the grammar of Section 6.3 to include the 'unary minus' (i.e. an arithmetic operator that turns any expression into its negative, as in –x). Do this under two different assumptions: (a) The unary minus is denoted by a different character than the binary minus, say ¬. (b) The character – is 'overloaded' (i.e. it is used to denote both unary and binary minus). For any specific occurrence of –, only the context determines which operator it designates. 3. Extended Backus-Naur form and syntax diagrams Define each of the four languages described below using both EBNF and syntax diagrams. Use the following conventions and notations: Uppercase letters denote nonterminal symbols. Lowercase letters and the three separators ',' '(' and ')' denote terminal symbols. "" stands for the empty or null string. Notice that the blank character does not occur in these languages, so we use it to separate distinct sentences. 60
algorithms and data structures_Page_60_Chunk4600