Question Sheet 6 - Challenge Problem Example Answers

Note that, while in maths a function is typically something similar to f(x)=(x^2). When coding, a function is just something that has a dependence on a variable. So for example, the following plots, that are dependent on the value of ‘n’ in the argument of sign, can be defined as functions of n.

1 a) A student has defined two functions below. Which form is more appropriate and why?

f1[n_]:=Plot[Sin[n*x],{x,0,2π}]

g1[n_]=Plot[Sin[n*x],{x,0,2π}]

As we can see from above, ‘g1’ plots the function before we have specified a value for n. On the other hand, ‘f1’ delays the evaluation of the function until we have specified a value of n.

b) Evaluate the above code, and then plot f1(3) and g1(3) to test your predictions. Compare your prediction with the output and explain any differences between the output of the two functions.

f1[3]

g1[3]

We see that ‘g1’ does not plot the function because it has already evaluated the code before we specify a value for ‘n’.

2 a) Define two functions that plot (x^2) over an arbitrary range a to b (analogous to those in question 1). One should use ‘=’ and the other should use ‘:=’ to define the function.

f2[a_,b_]:=Plot[x^2,{x,a,b}]

g2[a_,b_]=Plot[x^2,{x,a,b}]

b) Do you expect either/both of the functions to work? Why/why not?

Considering the previous question we would probably expect ‘f2’ to work and ‘g2’ not to work. However ‘g2’ also works. Why is this? if we compare ‘g1’ and ‘g2’ we see that when we evaluate ‘g2’ we get an error. The plot function cannot evaluate if it doesn’t have a range to plot over. On the other hand, you can plot a blank graph:

Plot[,{x,0,1}]

So ‘g1’ can evaluate but the error acts to delay the evaluation of ‘g2’ until a range is specified.

c) Specify some values for a and b and evaluate both functions to test if they work.

f2[0,1]

g2[0,1]

d) Did your predictions match the results? Comment on any discrepancies.

3. A student has produced the code below to plot sin(n) for a range of values of n. Evaluate the code and comment on any errors the student has made.

f3[x_]:=Plot[Sin[n*x],{x,0,2π}]

f3[3]

Here the student has made the argument of the function ‘x’ insteand of ‘n’.

f4[n_]:=Plot[Sin[n*x],{x,0,2π}]

f4[3]