Tutorial A2 – Solutions

1 Consider the equation \(y = \frac{3a + 2b}{b^2}\), with \(a = 1\) and \(b = 2\).

  • Calculate \(y\) using Python.

[1]:
a = 1
b = 2
y = (3*a + 2*b) / b**2
print(y)
1.75
  • Of what type is the result?

[2]:
print(type(y))
<class 'float'>
  • How can you force the result to be a whole number?

[3]:
# Use integer conversion (flooring)
y_ = int(y)
print(y_, type(y_))
1 <class 'int'>
[4]:
# Use round() (closest integer)
y_ = round(y)
print(y_, type(y_))
2 <class 'int'>
  • Of what type is the result if \(b = 1\)?

[5]:
a = 1
b = 1
y = (3*a + 2*b) / b**2
print(y, type(y))  # Still a float because of division
5.0 <class 'float'>
  • What happens if \(b = 0\)?

[6]:
a = 1
b = 0
y = (3*a + 2*b) / b**2  # Raises an error!
print(y, type(y))
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-6-79b38353c79e> in <module>
      1 a = 1
      2 b = 0
----> 3 y = (3*a + 2*b) / b**2  # Raises an error!
      4 print(y, type(y))

ZeroDivisionError: division by zero

2 Calculate the gravitational force between the moon and the earth at a distance of \(r = 3.84\times 10^8\) m, with masses \(m_\mathrm{earth} = 5.97\times 10^{24}\) kg, \(m_\mathrm{moon} = 7.35\times 10^{22}\) kg. Use \(G = 6.67 \times 10^{-11}\) m\(^3\) kg\(^{-1}\) s\(^{-2}\) for the gravitational constant.

[7]:
r = 3.84e8
m_earth = 5.97e24
m_moon = 7.35e22
G = 6.67e-11

F = (G * m_earth * m_moon) / r**2
print("Gravitational force: ", F, "N")
Gravitational force:  1.9848379516601562e+20 N

Advanced 1 How does Python handle infinity and absent numeric values? What is the result of a multiplication of these values with 0?

Note: Advanced exercises are not mandatory to get the points.

[8]:
print(float('nan') * 0)
nan
[9]:
print(float('inf') * 0)
nan