#### 1.2.1 Defining a function ¶

Consider a damped sine wave. It describes the time evolution of an oscillator, such as a weight on a spring, which bobs up and down for a while after you whack it. The basic shape of the wave is determined by the Q of the oscillator; a high Q means there is little friction, and the weight will continue bobbing for many cycles, while a low Q means a lot of friction and few cycles. The amplitude of the oscillation is therefore a function of two parameters – the phase (time in units of the natural period of the oscillator), and the Q:

    func damped_wave(phase, Q)
    {
      nu = 0.5/Q;
      omega = sqrt(1.-nu*nu);
      return sin(omega*phase)*exp(-nu*phase);
    }

Within a function body, I terminate every Yorick statement with a semicolon (see Defining a variable).

The variables `phase` and `Q` are called the parameters of the function. They and the variables `nu` and `omega` defined in the first two lines of the function body are local to the function. That is, calling `damped_wave` will not change the values of any variables named `phase`, `Q`, `nu`, or `omega` in the calling environment.

In fact, the only effect of calling `damped_wave` is to return its result, which is accomplished by the `return` statement in the third line of the body. That is, calling `damped_wave` has no side effects. You can use `damped_wave` in expressions like this:

    > damped_wave(1.5, 3)
    0.775523
    > damped_wave([.5,1,1.5,2,2.5], 3)
    [0.435436,0.705823,0.775523,0.659625,0.41276]
    > q5 = damped_wave(theta,5)
    > fma; plg, damped_wave(theta,3), theta
    > plg, damped_wave(theta,1), theta

The last two lines graphically compare Q=3 oscillations to Q=1 oscillations.

Notice that the arguments to `damped_wave` may be arrays. In this case the result will be the array of results for each element of input; hence `q5` will be an array of 200 numbers. Nor is Yorick confused by the fact that the `phase` argument (`theta`) is an array, while the `Q` argument (`5`) is a scalar. The precise rules for “conformability” between two arrays will be described later (see Broadcasting and conformability); usually you get what you expected.

In this case, as Yorick evaluates `damped_wave`, `nu` and `omega` will both be scalars, since `Q` is a scalar. On the other hand, `omega*phase` and `nu*phase` become arrays, since `phase` is an array. Whenever an operand is an array, an arithmetic operation produces an array as its result.