Home Page > > Details

IN1900 Assignment, Python Programming Assignment,Python AssignmentHelp With ,Help With programming AssignmentHelp With R Programming| C/C++ Programming

Exercises for IN1900
October 14, 2019
Preface
This document contains a number of programming exercises made for the course
IN1900. The chapter numbers and titles correspond to the chapters of the book
“A primer on Scientific Programming with Python” by Hans Petter Langtangen.
The exercises are meant to be a supplement to the exercise collection in the book,
and most are motivated by applications in science and applied mathematics.
The exercise collection is used for the first time in 2018, and there may be typos
and small errors. If you find any errors, or have other comments or questions
about the exercises, please send them to Joakim Sundnes: sundnes@simula.no.
1
Chapter 1
Computing with Formulas
Problem 1.1. Throw a ball
When throwing a ball in the air, the position of the ball can be calculated using
the acceleration of the ball. When neglecting air resistance, the acceleration will
be the negative of the gravitational constant, −g. The height of the ball relative
to its starting point is
y(t) = v0t −12gt2,
where v0 is the initial velocity of the ball and t is the time after the throw. The
ball reaches its maximum height at time
tmax =v0g.
Write a program computing the maximum height of the ball, that is y(tmax),
when v0 = 8.2m/s and g = 9.81m/s2. Print the result.
Filename: ball.py
Problem 1.2. Population growth
The growth of a population can often be described by a logistic function
N(t) = B1 + Ce−kt ,
where B is the carrying capacity of the species in the environment, i.e., the
maximum size of the population that the environment can sustain indefinitely.
The constant k tells us something about how fast the population grows, while C
is given by the initial conditions. Let us consider a bacterial colony where we
take the carrying capacity to be B = 50000 and k = 0.2h−1. If the population is
5000 at t = 0, find C and write a code that finds the number of bacteria in the
colony after 24 hours.
Filename: population.py
2
Problem 1.3. Solve the quadratic equation
Given a quadratic equation
ax2 + bx + c = 0,
the two roots are.
Make a program evaluating the roots of.
Print out both roots with two decimals.
Filename: find_roots.py
Problem 1.4. Forces in the hydrogen atom
There are two kinds of forces acting between the proton and the electron in the
hydrogen atom; Coulomb force and gravitational force. The Coulomb force can
be expressed as,
where ke is Coulomb’s constant, e is the elementary charge, and r is the distance
between the proton and the electron.
The gravitational force can be expressed as
FG = Gmpmer2,
where G is the gravitational constant, mp is the mass of the proton, me is the
mass of the electron, and r is the distance between the particles.
We can use these expressions for FC and FG to illustrate the difference in
strength of these two forces, i.e., the electromagnetic force and gravitational force.
Use the values ke = 9.0·109 Nm2C
−2
, e = 1.6·10−19 C, G = 6.7·10−11 Nkg−2m2
,
mp = 1.7·10−27 kg and me = 9.1·10−31 kg.You can take the distance between the
proton and electron to be approximately the Bohr radius r = a0 = 5.3 · 10−11 m.
Make a program that computes both the Coulomb force and the gravitational
force between the proton and the electron. Write out the forces in scientific
notation with one decimal in units of Newton (N = kgm/s
2
). Also print the
ratio between the two forces.
Filename: hydrogen.py
3
Chapter 2
Loops and Lists
Problem 2.1. Multiply by five
Write a code printing out 5 · 1, 5 · 2, ..., 5 · 10, using either a for or a while loop.
Filename: multiplication.py
Problem 2.2. Multiplication table
Write a new code based on the one from Problem 2.1. This code should print
the whole miltiplication table from 1 · 1 to 10 · 10.
Hint: You may want to consider using one loop inside another.
Filename: mult_table.py
Problem 2.3. Stirling’s approximation
Stirling’s approximation can be written ln(x!) ≈ x ln x − x. This is a good
approximation for large x. Write out a nicely formatted table of integer x values,
the actual value of ln(x!), and Stirling’s approximation to ln(x!).
Filename: stirling.py
Problem 2.4. Errors in summation
The program has three errors and therefore does not work. Find the three errors
and write a correct program. Put comments in your program to indicate what
the mistakes were.
Hint: There are two basic ways to find errors in a program:
1. read the program carefully and think about the consequences of each
statement,
2. print out inter mediate results and compare with hand calculations.
4
1. First, try method 1 and find as many errors as you can. Thereafter, try method
2 for M D 3 and compare the evolution of s with your own hand calculations.
Lastly, write a similar code evaluating the same sum using a while loop.
Check that the two loops compute the same answer.
Filename: sum_for.py
5
Problem 2.5. Binomial coefficient
The binomial coefficient is indexed by two integers n and k and is written . Compute the same value using Eq. (2.1) and check that the results are
correct.
Hint: The Q
sign is a product sign.
When checking the result you will need math.factorial.
Filename: binomial.py
Problem 2.6. Table showing population growth
Consider again the bacterial colony from Problem 1.2. Let us study the number
of individuals for n + 1 uniformly spaced t values throughout the interval [0, 48].
Set n = 12. First store the t and N values in two lists t and N. Thereafter, write
out a nicely formatted table of t and N values by traversing the two lists with a
(separate) for loop.
Filename: population_table.py
Problem 2.7. Nested list
a) Compute two lists of t and N values as explained in Problem 2.6. Store the
two lists in a new nested list tN1 such that tN1[0] is the list containing t-values
and tN[1] correspond to the list containing N-values. Write out a table with t
and N values in two columns by looping over the data in the tN1 list. Each t
and N value should be written in the table as integers.
b) Make a nested list tN2 where tN2[i] contains the i-th element of both the
t-list and the N-list. Loop over the tN2 list and write out the t and N values in
the table as integers.
Filename: population_table2.py
Problem 2.8. Calculate Cesaro mean
Let (an)∞n=1 be a sequence of numbers, sk =Pkn=0 an = a0 + . . . , +ak,
is called a Catalan number. Compute and print the first 10 Catalan numbers.
Filename: catalan.py
Problem 2.10. Molar Mass of Alkanes
Alkanes are saturated hydrocarbons with the chemical formula CnH2n+2. If
there are n Carbon atoms in the alkane, there will be m = 2n + 2 Hydrogen
atoms. The molar mass of the hydrocarbon is MCnHm = nMC + mMH, where
MC is the molar mass of Carbon and MH is the molar mass of Hydrogen.
Use a for-loop or a while-loop to compute and print out the molar mass
of the alkanes with two through nine Carbon atoms (n ∈ [2, 9]). The output
should specify the chemical formula of the alkane as well as the molar mass. An
example on how the formatted output should look like for n = 2 is given below.
M(C2H6) = 30.069 g/mol
You can set the molar masses of the atoms to be MC = 12.011 g/mol and
MH = 1.0079 g/mol
Filename: alkane.py
Problem 2.11. Matrix elements
This exercise involves no programming.
The answers should be written in a text file called matrix.txt
Consider a two dimensional 3 × 3 matrix
In Python, the matrix A can be represented as a nested list A, either as a
list of rows or a list of columns. Find the indices i, j of the Python list A such
that A[i][j] = a11 and the indices k, l such that A[k][l] = a32 for the two
following cases:
a) When A is represented as a list of rows. This means that A contains three
lists, where each list corresponds to a row in A.
b) When A is represented as a list of columns. This means that each element
in A contains a list with the elements of a column in A.
Filename: matrix.txt
7
Chapter 3
Functions and Branching
Problem 3.1. Implement a function for population growth
Consider again the function
N(t, k, B, C) = B
1 + Ce−kt .
Implement N as a python function population(t, k, B, C) that returns the
number of individuals in a population after a time t.
Write out a nicely formatted table of t and N values for the time interval
t ∈ [0, 48] using the values from Problem 2.6.
Filename: pop_func.py
Problem 3.2. Sum of integers
We consider the sum Pn
i=1 i = 1 + 2 + · · · + n of positive integers up to n. It
can be shown that the sum is equal to n(n+1)
2
.
a) Write a function sumint(n) that returns the sum of all positive integers
up to n.
b) Write a function implementing n(n+1)
2
.
c) Write test functions for both a) and b) testing for specific known values.
Filename: sumint.py
Problem 3.3. Implement the factorial
a) The factorial can be implemented by a so called recursive function call. Use
a recursive function call to implement a function myfactorial(n) that returns
n!.
b) Write a test function where you call the myfactorial function and check
the value of the returned object for one value of n using math.factorial.
Filename: factorial.py
8
Problem 3.4. Half-wave rectifier
In a half-wave rectifier the positive part of a signal passes, while the negative
part is blocked. Thus, for a signal passing through a half-wave rectifier, the
negative values are set to zero. Let us look at a sine signal that has passed
through a half-wave rectifier:
f(x) = (
sin x if sin x > 0
0 if sin x ≤ 0.
Implement f(x) as a Python function f(x) and make a test function for testing
the implementation of f(x) in both cases.
Filename: half_wave.py
Problem 3.5. Compute the area of an arbitrary triangle An arbitrary triangle
can be described by the coordinates of its three vertices: (x1, y1),(x2, y2),(x3, y3),
numbered in a counterclockwise direction. The area of the triangle is given by
the formula
Write a function triangle_area(vertices) that returns the area of a triangle
whose vertices are specified by the argument vertices, which is a nested list of
the vertex coordinates. Make sure your implementation passes the following test
function, which also illustrates how the triangle_area function works:
def test_triangle_area():
"""
Verify the area of a triangle with vertices
(0,0), (1,0), and (0,2).
"""
v1 = (0,0); v2 = (1,0); v3 = (0,2)
vertices = [v1, v2, v3]
expected = 1
computed = triangle_area(vertices)
tol = 1E-14
success = abs(expected - computed) < tol
msg = f"computed area={computed} != {expected}(expected)"
assert success, msg
Filename: triangle_area.py
Problem 3.6. Primality checker
Recall that a prime number is a number greater than 1 that has exactly 2 divisors.
Said differently, a number greater than one is a prime if it is divisible by only
itself and one. A number that is not prime is called composite. Every number n
can be written as a unique product of primes (e.g. 12 = 2 · 2 · 3), this is called
the prime factorization of n.
a) Make a function that takes a number n, and returns true if it’s prime, and
false if it’s not. Use the program to find all prime numbers up to 100.
p
Hint: You will only need to check divisibility for numbers up to and including
(n), because any greater divisor will imply that there is a divisor less than this.
9
b) Make a function that instead finds the prime factorization of the input
number. It should print “prime” and return nothing if the number is prime,
and both print and return the factorization if it’s composite. Find the prime
factorization of 5525612.
c) Make test functions for the two functions above where you check for small
values of n.
d) Compare the runtime of the two functions with the number 33425626272.
Is the difference big? If so, why do you think one is faster than the other? The
following code returns the mean time it takes for your program to run once:
import timeit
timeit.timeit(’your_func(args)’, \
’from __main__ import your_func’,number=1)
Filename: prime.py
Problem 3.7. Eulers totient function
Two numbers n and m are called relatively prime if they have no common divisors
except for 1. That is, no number greater than one should divide both numbers
with no residue.
a) Make a function that takes two numbers and returns true if they’re relatively
prime and false if they’re not.
b) Euler’s totient function is defined as
φ(d) = #{Numbers less than d which are relatively prime to d}.
Implement Eulers totient function and print φ(d) for d = 10, 50, 100, 200.
c) Make a test function for both a) and b).
Filename: euler.py
Problem 3.8. Simple Statistical Functions
In this problem you will implement two statistical functions and test them by
comparing the results with statistical functions from the numpy module. We will
trust that the functions from the numpy module are correct, and will use them
as benchmark values in the test functions. When you import the numpy module
you should follow the convention of renaming it np, as shown below.
import numpy as np
a) The mean of a set of numbers x1, x2, x3, ..., xN is defined as
where N is the size of the set. Implement a function mean(x_list) that returns
the mean value of a list of numbers.
10
b) Make a test function test_mean() that tests the function from a). Compare
the returned value with the result from numpy.mean. (Such that
expected =np.mean(x_test_values)).
c) The standard deviation of a set of numbers x1, x2, x3, ..., xN is defined as.
Implement a function standard_deviation(x_list) which returns the standard
deviation of a list of numbers. The mean value of the list will be necessary
to calculate the relative deviation. Obtain the mean value inside the
standard_deviation function by calling the function you made in a).
d) Make a test function test_standard_deviation() that tests the function
from c). Compare the returned value with the result from numpy.std. (Such
that expected =np.std(x_test_values)).
You may use the list below as an example for your test functions.
x_test_values = [0.699, 0.703, 0.698, 0.688, 0.701]
Filename: stat.py
Problem 3.9. Münchhausen Numbers
A Münchhausen number is a number such that the sum of every digit to the
power of itself equals the original number. E.g. 1
1 = 1 is a Münchhausen number,
and 5
5 + 33 + 22 = 3156 6= 532, so 532 is not.
Make a function that checks if a number is Münchhausen. Find a Münchhausen
number different from one.
Hint: There is only one such number different from 1 and also under one
million
Filename: m_numbers.py
11
Chapter 4
User Input and Error
Handling
Problem 4.1. Quadratic with user input
Consider the usual formula for computing solutions to the quadratic equation
ax2 + bx + c = 0 given by.
Write a program that asks the user for values ( a =, b = and c = ) to get values
for a, b, and c through the users keyboard. Use input (or raw_input if you are
using Python 2). Print the solutions.
Filename: quadratic_roots_input.py
Problem 4.2. Quadratic with command line
Modify the program from 4.1 such that a, b and c are read from the command
line.
Filename: quadratic_roots_cml.py
Problem 4.3. Quadratic with exceptions
Extend the program from 4.2 with exception handling such that missing command
line arguments are detected. In the except IndexError block, use input (or
raw_input if you are using Python 2) to ask the user for missing input data.
Filename: quadratic_roots_error.py
Problem 4.4. Quadratic with raising Error
In this exercise, use the sqrt function imported from math.
Consider the program from Problem 4.1. Not all inputs yield real solutions.
Modify the program such that it raises ValueError if the values for a, b and c
yield complex roots. (That is if b
2 −4ac < 0). Provide a suitable Error-message.
Test that your program prints out real roots and that it raises ValueError when
the roots are complex. (An example of values that provide complex roots could
be a = 1, b = 1, c = 1, while a = 1, b = 0, c = −1 provide real roots).
Filename: quadratic_roots_error2.py
12
Problem 4.5. Estimating harmonic series
Let f(x) be the function
Write a program that approximates f(x) (that is, evaluates fN (x) = PN
with values of x and N given as command line arguments. Run the program for
x = 0.9, x = 1, and N = 10000. Print the results.
Remark. For x = 1 this is known as the harmonic series. Despite the low values
for large N, the series does not converge, but diverges very slowly. Try to run
the program for different values of N to see how big you can get the value of
f(1).
Filename: harmonic.py
Problem 4.6. Estimating harmonic series extended
Using the program from Problem 4.5, consider the following values for x and N
in a text file
x: 0.9 1
N: 500 1000 10 100 50000 10000 5000
a) Write a function to read a file containing information in the above format
that returns two lists containing the values of x and N.
b) Write a test function for a) that generates a file in the given format and
checks that the values returned by the function is correct.
c) Use the program from Problem 4.5 to evaluate fN (x) for the different values
of x and N. Create a function that writes the information to a file in a table
format with the first column containing the values of N in increasing order, and
the second and third the values of fN (x) at 0.9 and 1 respectively.
Filename: harmonic_table.py
Problem 4.7. Read isotope file
Isotopes of a chemical element in its ground state have the same number of
protons but differ in the number of neutrons. The weight of isotopes of the same
chemical element will therefore be different.
The molar mass, M, of a chemical element, can be calculated by summing
over all its isotopes M =Pi miwi, where mi
is the weight of the i-th isotope
and wi the corresponding natural abundance.
The file Oxygen.txt, which is given below, contains the information on
Oxygen’s isotopes (16O,
17O and 18O).
Isotope weight [g/mol] Natural abundance
(16)O 15.99491 0.99759
(17)O 16.99913 0.00037
(18)O 17.99916 0.00204
13
Write a script in Python to read the file Oxygen.txt and extract the weights
and the natural abundance of all the isotopes of Oxygen. Use these to calculate
the molar mass of Oxygen. Print out the result with four decimals and provide
the correct units.
Filename: read_file_isotopes.py
Problem 4.8. A result on prime numbers
A famous result concerning prime numbers states that the number of primes
below a natural number n, denoted π(n), is approximately given by
tends to 1 as n → ∞. The following
table contains the exact values of π(n) for some values of n.
n: 10**20 10**4 10**2 10**1 10**12 10**4 10**6 10**15
pi(n): 2220819602560918840 1229 25 4 37607912018 168
78498 29844570422669
a) Write a function that reads the file given above and returns two tuples
containing sorted values of n and π(n). It is important that the correspondence
in the orderings are correct, that is, the same as in the table above.
b) Write a test function that generates a file with the format above and tests
that the returned values are correct. It should test that the order of the elements
are in correspondence as in the file.
Hint: The == operator on tuples will take the order into account. The same
operator on lists will not.
c) Create a function that writes the values of n and p(n) to a file in a table
format in increasing order with the values of n in the first column and the
corresponding values of p(n) in the second column.
Bonus problem There are better approximations to π(n), for example the
function
Approximate the integral for different values of n and modify the program to
write these into a third column.
Hint: Implement an algorithm for approximating the integral (e.g. the
trapezoidal rule) and compute the difference as before.
Filename: primes.py
14
Problem 4.9. Conversion from other bases
Recall that a binary number is a sequence of zeros and ones which converted to
the decimal system becomes P
i
2
i where i is a term in the sequence containing
a 1 (e.g. 100101 = 25 + 22 + 20 = 37).
a) Write a function that takes a binary number and converts it to a decimal
number. If the argument is not a binary number, a message should be printed
and nothing returned.
Hint: Let the number in the argument be of type string to avoid problems
with numbers starting with a zero.
b) Let the binary number from a) be taken as a command line argument.
Use exceptions (IndexError) to handle missing input. Print the conversion of
100111101.
c) Extend the program with a function to also handle numbers written in base
3.
Hint: An example of a ternary number(a number in base 3) converted to a
decimal number: 1201 = 1 · 3
Filename: base_conversion.py
Problem 4.10. Read temperatures from two files
We consider data sets from the Norwegian Meteorological Institute, containing
daily mean temperatures of any month of any year at Blindern (Oslo).[Ins19]
Each file looks typically like this:
Year: 1997. Month: April. Location: Blindern(Oslo)
9.0 12.3 15.8 13.4 11.0 16.2 13.3
12.9 14.0 14.1 12.0 17.3 15.5 15.4
...
The observations are given chronologically, and the temperatures are given in
degrees Celsius. There are no empty lines in the bottom of the file.
a) Write a function extract_data(filename) that reads any such file and
returns a list of the temperatures from the given month.
b) In the two files temp_oct_1945.dat and temp_oct_2014.dat you will
find observations of daily mean temperatures in October 1945 and October
2014, respectively. Store the temperatures in two lists oct_1945 and oct_2014.
Calculate the average, maximum and minimum value of the temperatures of both
months, and print the results. You may use the numpy.mean(), numpy.max()
and numpy.min() methods.
c) Write a function write_formatting() that takes at least filename, list1
and list2 as parameters, and creates a new file with two nicely formatted
columns containing the temperatures of the given months (you can assume that
the months have equal lengths). Finally, call the function such that the file
temp_formatted.txt is created, using the lists oct_1945 and oct_2014.
Filenames: temp_read_write.py, temp_formatted.txt
15
Chapter 5
Array Computing and
Curve Plotting
Problem 5.1. Fill arrays; loop version
We study the function
f(x) = ln(x).
We want to fill two arrays x and y with x and f(x) values, respectively. Use 101
uniformly spaced x values in the interval [1, 10]. Create empty x and y arrays
and compute each element in x and y with a for loop.
Filename: fill_log_arrays_loop.py
Problem 5.2. Fill arrays; vectorized version
Vectorize the code in Problem 5.1 by creating the x values using the linspace
function from the numpy package and evaluating f(x) with an array argument.
Since the calculation should be vectorized, you may not use any form of loop.
Filename: fill_log_arrays_vectorized.py
Problem 5.3. Plot the population growth
Again, we’re considering a population undergoing logistic growth. The number
of individuals in the population is given by
N(t, k, B, C) = B
1 + Ce−kt .
Plot this function for t ∈ [0, 48] with a carrying capacity B = 50000, C = 9 from
the initial condition that we have 5000 individuals at t = 0 and a steepeness of
k = 0.2.
Filename: population_plot.py
Problem 5.4. Oscillating spring
A rock of mass m is hung from a spring, and pulled down a length A. When
released, the rock will oscillate up and down with a vertical position given by
y(t) = Ae−γt cos r
Here, y is the vertical position of the rock, k is the spring constant, and γ is
a friction coefficient representing air resistance. Set k = 4 kg s−2 and γ = 0.15
s
−1
, m = 9 kg, and A = 0.3 m.
16
a) Create arrays t_array and y_array of size 101, both initially filled with
zeros. Use a for loop to fill them with time values in the range from 0 to 25
seconds, and the corresponding y(t) values.
b) Vectorize your program by using the NumPy’s linspace function to generate
the t_array, and send it into a function y(t) to generate the y_array.
Your program should now be free of for loops. paragraphc) Plot the position
of the rock against time in the given time interval. Use the arrays from both
exercise a) and b), and confirm that they give the same result. Put the correct
units on both axes.
Filename: oscillating_spring.py
Problem 5.5. Plot Stirling’s approximation
Stirling’s approximation is
ln(x!) ≈ x ln x − x.
a) Make two functions stirling(x) and exact(x), returning Stirling’s approximation
and the exact value of ln(x!), respectively. Plot both the approximation
and the exact curve in the same figure.
Hint: To implement a vectorized version of the exact function, you can use
scipy.special.gamma(x). This function is a “generalized factorial” which can find
the “factorial” of float numbers. It works such that n! = gamma(n + 1). You
can also just consider integer values and plot the value of ln(x!) for each integer
x in the interval you’re considering. Keep in mind that math.factorial is not
vectorized.
b) Use a while loop and find the minimal value of x for the relative error to
be less than 0.1%.
Hint: Relative error is given as (a − a˜)/a, where a is the exact value and a˜
is the approximation. Also, do not start with x smaller than or equal to 1, why?
Filename: stirling_plot.py
Problem 5.6. Plotting roots of a complex number
The n’th roots of a complex number z = reiθ can be found by,
for k = 0, 1, ..., n − 1. The roots can be rewritten to separate the real component
xk and the imaginary component yk, such that ωk = xk + iyk. Through the
relation between the exponential function and the sine functions we get,
for k = 0, 1, ..., n − 1.
17
a) Write a function that takes the angle θ, the radius r and the degree n of
the roots as parameters. The function should calculate and return all of the n’th
roots of a complex number reiθ, as two lists or arrays corresponding to the real
part x = x0, x1, ..., xn−1 and the complex part y = y0, y1, ..., yn−1 of the roots.
An example of a function call on the function you will write is given below.
x, y = roots(r, theta, n)b) Consider the complex number z = 10−4e
i2π
. Use the function from a) to
get all the roots of order n = 6, n = 12 and n = 24. Plot the roots as points,
and plot all the three orders of roots in the same plot. Label the different orders
of roots. And example of code for plotting the roots of order n = 6 is given
below.
plt.plot(x_n_6, y_n_6, "o", label="n = 6")
Filename: roots.py
Problem 5.7. Fermi-Dirac distribution
The Fermi-Dirac distribution says something about the probability of an energy
state being occupied by a particle, or more precisely a fermion, e.g. an electron.
It is a function of energy and temperature given by
f(E, T) = 1
1 + e
(E−µ)/kT , (5.1)
where E is energy, T is temperature, k is Boltzmann’s constant and µ is the
so-called chemical potential. Use k = 8.6 · 10−5
eVK−1 and µ = 4.74eV and
make a program that visualizes the Fermi-Dirac distribution on the interval
E ∈ [0, 10]eV when T = 0.1K. (eV is a unit of energy, 1eV = 1.6 · 10−19J.)
Filename: Fermi_Dirac.py
Problem 5.8. Animate the temperature dependence of the FermiDirac
distribution
Make an animation of the Fermi-Dirac distribution f(E, T) from Problem 5.7
We’re interested in studying how the distribution changes when we raise the
temperature. Plot f as a function of E on [0, 10] for a set of temperatures
T ∈ [0.1, 3 · 104
]. Also make an animated GIF file. Remember to label your axes
and include a legend to show the value of the temperature.
Hint: A suitable resolution can be 1000 intervals (1001 points) along the E
axis, 60 intervals (61 points) in temperature, and 6 frames per second in the
animated GIF file. Use the recipe in Section 5.3.4 and remember to remove the
family of old plot files in the beginning of the program.
Filename: Fermi_Dirac_movie.py
Problem 5.9. Bump functions
Consider the function
f(x) = (
ke− 1
1−x2 −1 < x < 1
0 otherwise.
a) Plot the function with k = 1 on the interval −2 ≤ x ≤ 2 by implementing a
vectorized version in your program.
b) Animate the function on the same interval as above when k decreases from
1 to 0.
Filename: bump.py
Problem 5.10. Band structure of solids
Electrons in solids are waves. These waves have different wave lengths λ. Often,
waves are characterised by their wave number k = 2π/λ, and the wave number
is associated with the energy of the electron. The energies of electrons in solids
have a band structure, i.e., there are different bands of energies separated by a
band gap.
The file bands.txt contains k-values and corresponding energies for the
three first bands of a solid. Have your program read the values for k and the
energies and plot the energy bands as functions of k in the same figure. You will
see that some energies can never be obtained by electrons in the solids. These
areas of non-allowed energies are called the band gaps.
Filename: band_structure.py
19
Problem 5.11. Half-wave rectifier vectorized
In Problem 3.4, we implemented a function illustrating a sine signal after it had
passed through a half-wave rectifier. Vectorize this function and plot f(x) for
x ∈ [0, 10π].
Hint: The numpy.where(condition, x1, x2) function returns an array
of the same length as condition, whose element number i equals x1[i] if
condition is True, and x2[i] otherwise.
Filename: half_wave_vec.py
Problem 5.12. Singularity plot
In this problem we consider the function. Create arrays of r and θ values on the unit
circle centered at the origin with n uniformly spaced values. Fix axes between
-0.5 and 0.5 for x and y and visualize the function for n = 10, 50, 100, 500. You
can use the following to generate the correct values for r and θ:
theta = np.linspace(0,2*np.pi,100)
r = np.linspace(0.01,1,100)
r, theta = np.meshgrid(r,theta)
Remark. If we had an ideal computer that could calculate every value in an
interval and plot it, then the image we have plotted would touch every single
value in the plane, except for at most one! In our program we have 0.01 < r < 1.
The remarkable thing is that the same is true if we replace the inequality with
0 < r <  for any  > 0. Not only that, but all those points are hit an infinite
number of times!
Filename: ess_sing.py
Problem 5.13. Approximate |x|
The absolute value f(x) = |x| can be written as a sum.
Write a program that calculates the first N terms for N = 1, 2, 3, 4 and plots it
against the exact function. Let the x-axis be [−π, π] with a suitable y-axis.
Filename: approx_abs.py
Problem 5.14. Plotting graphs
A graph is a collection of lines and points in the plane such that each line
connects two points. In this exercise we will create functions for plotting graphs
on a set of points.
a) Make a function plot_line(p1,p2) that takes two points as input arguments
and plots the line between them. The two input arguments should be
lists or tuples specifying x- and y-coordinates, i.e. p1 =(x1,y1). Demonstrate
that the function works by plotting a vertical and a horizontal line.

Contact Us - Email:99515681@qq.com    WeChat:codinghelp
Programming Assignment Help!