Tutorial 2¶
Question 1¶
Use for
loops and print(end="")
to write functions which print the following patterns:
print_square(n)
wheren
is the number of stars along each edge.
*****
* *
* *
* *
*****
print_rhombus(n)
wheren
is the number of stars along each edge.
*****
* *
* *
* *
*****
print_numbers(n)
wheren
is the number at the centre.
1 1
2 2
3 3
4 4
5
4 4
3 3
2 2
1 1
Question 2¶
An integer \(n\) is a prime number if it is divisible only by 1 and \(n\).
Write a function
is_divisible(n, m)
which returnsTrue
ifn
is divisible bym
, and otherwise returnsFalse
.Write a function
is_prime(n)
which returnsFalse
ifn
is divisible by any integer between2
andn-1
, and otherwise returnsTrue
.Write a function
number_of_primes(n)
which returns the number of prime numbers less than or equal ton
[NB 1 is not a prime number].
Check the correctness of your functions by writing two tests for each.
Question 3¶
A solid of revolution is a three-dimensional figure contstructed by rotating a curve about a straight line. We can estimate the volume of a solid of revolution by dividing it into a sequence of stacked discs and summing the volume of each.
A sphere of radius \(R\) is formed by rotating the curve \(y = \sqrt{R^2 - x^2}\) around the x-axis between \(-R\) and \(R\).
Use the following steps to estimate the volume of a sphere of radius 1.
Write a function
vol_disc(R, x, dx)
which returns the volume of the disc centred at positionx
with thicknessdx
.Estimate the volume of a sphere of radius 1 by dividing the figure into 10 discs equally spaced between
-1
and1
[use a value of 3.14159 for \(\pi\)].Write a function
sphere_vol(R, n)
which returns the estimate of the volume of a sphere of radiusR
calculated by dividing it inton
discs.The estimate should get more accurate as we increase
n
. We can estimate the accuracy by calculating the difference betweensphere_vol(R, n)
andsphere_vol(R, n-1)
. ForR = 1
, how large doesn
need to be so that difference between consecutive estimates is less than \(10^{-4}\)?
Extension Questions (Optional)¶
These questions are open-ended and designed to allow to you challenge yourself beyond the material we have studied.
Investgate the Prime Number Theorem.
Write a function
volume_of_revolution(func, x_min, x_max, n)
which calculates the volume of the surface of revolution of the curve given by functionfunc
.func(x)
should be a function of a single variable which returns the y-value of the curve given the x value. You’ll have to learn how to pass a function as an argument to another function. Test your function by calculating the volume of a sphere, a paraboloid and another curve of your choice.