Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

How It Works

common2.jpg

Although the quad function may look more complicated than the other, more elementary examples in this chapter, at the bottom it’s doing the same thing: taking in some input, doing some number crunching, and returning a result. The one true innovation in this example is that here I’ve introduced the use of three arguments rather than just one.

The order of arguments is significant. Because the quad definition takes three arguments, a, b, and c, each call to quad must specify three values, and these are passed to those variable names: a, b, and c, in that order.

The following illustration shows how this works for the function call quad(1, 2, 1), assigning 1, 2, and 1 to the values a, b, and c:

Now it’s simply a matter of doing the correct number crunching to get an answer, and that means applying the quadratic formula.

040equ01.jpg

We can use pseudocode to express what this function does. A pseudocode description of a program or function uses sentences that are very close to human language but lists the steps explicitly.

Here is the pseudocode description of the quad function:

common1.jpg
For inputs a, b, and c:
     Set determ equal to the square root of (b * b) – (4 * a * c).
     Set x equal to (–b + determ) divided by (2 * a).
     Return the value x.

The quadratic formula actually produces two answers, not one. The plus or minus sign indicates that –b plus the determinant (the quantity under the radical sign) divided by 2a is one answer; but –b minus the determinant divided by 2a is the other answer. In Example 3.1, the function returns only the first answer.

common3.jpg

EXERCISES

Exercise 3.1.1. Revise the quad function by replacing the name determ with the name dt and by replacing the name x with the name x1; then verify that the function still works.

Exercise 3.1.2. Revise the quad function so that instead of returning a value, it prints two values using the Python print statement in a user-friendly manner: “The x1 value is…” and “The x2 value is…” (Hint: The use of the plus/minus sign in the quadratic formula indicates what these two—not one—values should be. Review this formula closely if you need to do so.) Print each answer out on a separate line.

Exercise 3.1.3. The mathematical number “phi” represents the golden ratio, more specifically, the ratio of the long side of a golden rectangle to the short side. Try to predict what the reciprocal (1/phi) is; then use the Python interactive environment to see whether you’re right. How would you express the relationship between phi and 1/phi?

  • + Share This
  • 🔖 Save To Your Account