PHYSICS 2235

### PHYSICS 2235 Lab 08

#### Exercise 1: Function Basics 1

#! /usr/local/bin/python3

import numpy as np
import matplotlib.pyplot as plt

#########################
def func(x):
"""Evaluate a function"""
return x**2 - np.sin(x)
#########################

x1 = np.linspace(0.1,10, 256)

plt.plot(x1,func(x1),'k-')
plt.show()


explaining code

Write a function that prints the statement "this function.." without it taking any arguments.

#### Exercise 1: Functions Basics 2

The variables created inside a function cannot be seen by the program itself. This is an important feature of writing a function. This means that you can create variables and arrays inside the function. Call them whatever you please and it would not be recognized or affect your main code. The only time you have access to a variable in a function is when you use the return statement.

import numpy as np
import matplotlib.pyplot as plt

def func(x):
a = x**2
b = 1/x
c = a * b
return c

var1 = 5.5
print(func(var1))

print(a)
print(b)
print(z)


• Note that your code does not run. Why does it complain?
• What variables can you read outside the function and what variables you can't.

#### Exercise 1: Functions Basics 3

It is important to note that you can use any variable name to assign the value for a function argument. The only restriction is that we can not use variables resevered by python (i.e. True, False, continue, from, not, and, or, else .. etc).
import numpy as np
import matplotlib.pyplot as plt

def func(x):
a = x**2
b = 1/x
c = a * b
return c

var1 = 5.5
print(func(var1))

#Your input variable/array can be called x or anything else
x = np.linspace(0.1,10, 256)
v = np.linspace(0.1,10, 256)
w = np.linspace(0.1,10, 256)


• plot func(x) vs. x, func(v) vs. v. on multiple subplots. Are they the same. Did you have any restrictions naming them?

#### Exercise 1: Basics 4

• Multiple variable input/output.
import numpy as np
import matplotlib.pyplot as plt

def xf(keyOpt,n):

if(keyOpt=='Yes'):
x= np.linspace(0, 180, n)
y= np.linspace(0, 580, n)
if(keyOpt=='No'):
x= np.linspace(0, 18, n)
y= np.linspace(0, 58, n)

return x,y

x1,y1 = xf('yes',150)

print (x1,y1)


explaining code
Note that there is a bug in your code. Find it and fix it.
Hint: Note that the string is case sensetive.

• non-variable output (plot, fig .. etc)
import numpy as np
import matplotlib.pyplot as plt

def xf(keyOpt,n):

if(keyOpt=='Yes'):
x= np.linspace(0, 180, n)
y= np.linspace(0, 580, n)
if(keyOpt=='No'):
x= np.linspace(0, 18, n)
y= np.linspace(0, 58, n)
print(x)
print(y)
plt.plot(y,x,'b--')
plt.savefig('line.png')
plt.show()

xf('Yes',150)


explaining code

#### Exercise 2:

import numpy as np
import matplotlib.pyplot as plt

def funcOpt(r,  n=12):
theta = np.pi/4;
x = r * np.cos(theta)
return x**n

a = funcOpt(3)
b = funcOpt(3, n=6)
c = funcOpt(3, n=4)


explaining code
• Another example you have used that includes positional arguments and keyword arguments is linspace linspace
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
which ones is the Keyword arguments and which ones is the positional arguments in this function?

#### Exercise 3: Looping over array in a function

The following absolute_value function works fine when the argument is a single variable.

def absolute_value(n):
if n < 0:
n = -n
return n

x=-50
y=absolute_value(x)

print (y)


Note here that the if statement is set up to evaluate the truth for a single variable. Not an element in an array. if you try.
x = np.linspace(-10, 10, 10)

y=absolute_value(x)

print (y)

In the main script. Your code will return an error. Try it.

One way to solve the problem is to have a for loop. For example:
def absolute_value(n):
y = np.zeros(n.size)
for i in range(n.size):# loops over all elements in  array
if n[i] < 0:
y[i] = -1*n[i]
else:
y[i] = n[i]
return y


x = np.linspace(-10, 10, 10)
y=absolute_value(x)
print(y)

Here the for loop evaluates the elements in the x array one by one and append the result. When its finished it will return an array.
Now try to use this last code for a single variable. Add the lines
x1=-50
y1=absolute_value(x1)

Note that it does not work for a single variable anymore.
Here we can use the where function from numpy. It:
• can handle single variables and arrays equally well
• simpler to write and read
• executes much faster, 25 to 100 times, depending on the size of the array where has the form
where(condition, output if True, output if False)

From the above example:
def simple_absolute(x):
z = np.where(x<0.0, -1*x, x)
return z

Now try to use this function for array and single variable.

#### Problem 1

Write a script that draws a smile and a frown face with eyes, mouth, and nose. Attached plots that illustrate the example can be found here:
• smiley face
• frown face

You are not required to reproduce the face in these examples exactly. In fact, have fun with the face and get creative if you like. However, you need to submit a face with eyes, mouth, and nose.

• The script needs to contain a function lets call it circle . The function should return 100 points in Cartesian coordinates (x,y) that lie on a circle. The default options should be that the circle origin is at the center (x0=0,y0=0), and that it will return (x,y) points lying on a full circle (thetai=0, thetaf=2pi). However, these are the default/keywords parameters. Meaning that the position of the circle can be changed by the user to not lie in the center nor be a full circle but part of a circle (i.e. thetai= 1/4*pi, thetaf=1/2*pi). The only mandatory/positional argument in this function is the radius of the circle.
def circle(r, x0=0.0, y0=0.0, thetai=0, thetaf=2*np.pi):

• Hint: Remember the polar to Cartesian coordinates function you have written in our (lab04- polcar.py).

• The second function lets call it plotface. The function plotface should have a positional/mandatory argument being the size of the face, the type of the face (smile or frown). The keyword argument being the color of the face (default being blue). The function plotface uses the function circle and should return a figure saved under the name smile.png if the option of the face type is 'smile' and should return frown.png if the option of the face type is 'frown'. Submit your code face.py together with smile.png and frown.png.

def plotface(r, faceType, stcol = 'b-'):

Note that the aspect ratio in python is off by default. Add the line plt.axes().set_aspect('equal') before you use plt.show() in order to fix that so your circle looks like a circle.

#### Problem 2

Write a function that returns the value of sinc(x) = sin(x)/x for single variables (-10,-8,0,8,10) and an array. The array here will range from -10 to 10. Make sure you have one function that can deal with both single variable and arrays.

• plot of sinc(x) vs. x .
• Add a title to your plot.
• Make sure you include enough points in the array that your plot is smooth.
• Submit the code sincx.py and the plot sincx.png
Important note: from the Taylor series of sinc(x):
\mathrm{sinc}\,x = \frac{\sin x}{x} = \frac{x - \frac{x^3}{3!} + \frac{x^5}{5!} + ...}{x} = 1 - \frac{x^2}{3!} + \frac{x^4}{5!} + ... \;.

From the Taylor series it is clear that when x=0 sinc(x)=1. Make sure that your function behaves properly around x = 0.

Back to main Physics 2235 page