sicp.io
2.4.1 · Multiple representations for complex numbers

One complex number can keep two useful coordinate systems.

Rectangular contents make addition direct, polar contents make multiplication direct, and tagged selectors present both as one abstract complex number.

Guiding question

How can one complex-number interface preserve the advantages of rectangular and polar representations at the same time?

  • Construct rectangular contents from real and imaginary parts
  • Construct polar contents from magnitude and angle
  • Dispatch common selectors through a representation tag
  • Use rectangular coordinates for addition and polar coordinates for multiplication
  • Compare inexact trigonometric observations with an explicit tolerance

A rectangular object stores x and y, so real-part and imag-part are direct while magnitude and angle are computed. A polar object stores r and a, so magnitude and angle are direct while real-part and imag-part are computed. The outer tag is a representation fact; it is not part of the abstract complex value seen by client code.

The first program constructs 3 + 4i in both forms and asks the same four selectors to observe them. close? records that the inexact trigonometric path agrees within a stated tolerance. The second program adds through real and imaginary parts and deliberately returns a rectangular object, while multiplication combines magnitudes and angles and returns a polar object. Generic selectors verify the abstract results without exposing either object’s contents to the caller.

SICP code1,914 of 1,048,576 UTF-8 bytes
Examples
Result
Output
Value
Diagnostic
Execution trace0 / 0 events
    Programs run in the browser with their result and execution trace.
    Expected result

    The first program returns (rectangular polar #t #t #t #t). The second returns (rectangular polar #t #t #t #t #t #t).

    Trace focus

    Follow the outer type tag before each selector chooses rectangular or polar contents. In the first run, compare direct selectors with the sqrt, atan, sin, and cos path. In the second, notice that addition constructs rectangular contents while multiplication constructs polar contents, then watch the same generic selectors verify both results. The tolerance defines equality for these finite inexact calculations.

    Try it yourself

    Change the program and compare the result.

    Represent -3 + 4i in both forms using magnitude 5 and angle (atan 4.0 -3.0). Reuse close? to verify all four selectors, then explain why the two-argument atan matters outside the first quadrant.

    Show hint

    The signs of both coordinates determine the quadrant. A one-argument atan of y divided by x loses that distinction.

    Complete this lesson

    0 of 20 lessons complete in this chapter0%