3.13: Exercises

Matlab and Octave Programming for STEM Applications · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    Read aloud

    How

    Speed: 1×
    Light up
    Highlight

    Symbols: Mulberry Symbols, © 2018–2026 Steve Lee, CC BY-SA 4.0 (licence, the set), the site's own copies.

    From LibreTexts, under CC BY-NC-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    3.13: Exercises

    Before you go on, you might want to work on the following exercises.

    Exercise \(3.5\)

    Years ago I was in a fudge shop and saw a sign that said “Buy one pound of fudge, get another quarter pound free.” That’s simple enough.

    But if I ran the fudge shop, I would offer a special deal to anyone who could solve the following problem:

    If you buy a pound of fudge, we’ll give you another quarter pound free. And then we’ll give you a quarter of a quarter pound, or one-sixteenth. And then we’ll give you a quarter of that, and so on. How much fudge would you get in total?

    Write a script called fudge.m that solves this problem. Hint: start with series.m and generalize it by replacing the ratio 1/2 with a variable, r.

    Exercise \(3.6\)

    We have already seen the Fibonacci sequence, \(F\), which is defined recurrently as

    \[\mathrm{for}~i \ge 3, \quad F_{i} = F_{i-1} + F_{i-2} \notag\]

    In order to get started, you have to specify the first two elements, but once you have those, you can compute the rest. The most common Fibonacci sequence starts with \(F_1 = 1\) and \(F_2 = 1\).

    Write a script called fibonacci2.m that uses a for loop to compute the first 10 elements of this Fibonacci sequence. As a postcondition, your script should assign the 10th element to ans.

    Now generalize your script so that it computes the \(n\)th element for any value of n, with the precondition that you have to set n before you run the script. To keep things simple for now, you can assume that n is greater than 0.

    Hint: you’ll have to use two variables to keep track of the previous two elements of the sequence. You might want to call them prev1 and prev2. Initially, prev1 = \(F_1\) and prev2 = \(F_2\). At the end of the loop, you’ll have to update prev1 and prev2; think carefully about the order of the updates!


    This page titled 3.13: Exercises was last modified on Wed, 13 Jul 2022 23:38:20 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.