Solutions

Learn the solutions to the exercises from the previous lesson.

We hope you’ve dedicated time to try to solve the exercises. Please remember that this kind of practice will help you grasp the content faster and better.

In case you want to check if your answer is right or if you got stuck in some of those exercises, we’ll solve all of them here. Let’s get started!

Exercise 1: The can of soda

Now we’re going to solve, once and for all, the problem of the soda can. Last time, we needed to add a restriction because we didn’t know how to calculate minima exactly.

To solve this problem, we can employ the code to calculate minima and maxima using the derivative, and substitute the function for the one that describes the surface of the can.

Press + to interact
from sympy import symbols, diff, Eq, solve, pi
# Define symbols
x = symbols('x', real=True)
# Define function
f = 710/x + 2*pi*x**2
# Calculate derivative
df = diff(f, x) # derivative of f with respect to x
# Print derivative
print(f"Derivative: {df}")
# Solve derivative
equation = Eq(df, 0) # equation is df = 0
solutions = solve(equation, x) # solve equation for x
print(f"Solutions: {solutions}")
# Determine if solutions are minima or maxima
eps = 0.1 # small number
for solution in solutions: # for every candidate point
before = df.subs(x, solution - eps) # f'(x - eps)
after = df.subs(x, solution + eps) # f'(x + eps)
if before < 0 and after > 0: # if it goes from - to +
print(f"Solution {solution} is a minimum")
elif before > 0 and after < 0: # else if it goes from + to -
print(f"Solution {solution} is a maximum")
else: # otherwise it is not a minimum nor a maximum
print(f"Solution {solution} is neither a minimum nor a maximum")

That’s it! Using the same code and substituting our function of interest is enough to solve the problem. There is an issue though. The solution is printed as a large expression that we need to evaluate after. This is because SymPy is a library for symbolic computing. It’s designed to solve problems in the same way we’d do on paper. To get the simplified solution, we’ll add a line of code right after the current line 17.

Press + to interact
from sympy import symbols, diff, Eq, solve, pi, N
# Define symbols
x = symbols('x', real=True)
# Define function
f = 710/x + 2*pi*x**2
# Calculate derivative
df = diff(f, x) # derivative of f with respect to x
# Print derivative
print(f"Derivative: {df}")
# Solve derivative
equation = Eq(df, 0) # equation is df = 0
solutions = solve(equation, x) # solve equation for x
# Get the numeric result
solutions = list(map(N, solutions))
print(f"Solutions: {solutions}")
# Determine if solutions are minima or maxima
eps = 0.1 # small number
for solution in solutions: # for every candidate point
before = df.subs(x, solution - eps) # f'(x - eps)
after = df.subs(x, solution + eps) # f'(x + eps)
if before < 0 and after > 0: # if it goes from - to +
print(f"Solution {solution} is a minimum")
elif before > 0 and after < 0: # else if it goes from + to -
print(f"Solution {solution} is a maximum")
else: # otherwise it is not a minimum nor a maximum
print(f"Solution {solution} is neither a minimum nor a maximum")

To get the value of the solution instead of an expression, we apply the function N to each solution. We import N from SymPy in line 1 and then apply it to every solution in line 20. To apply a function to every element in a list, we use Python’s built-in map function. The result of the map is converted to a list. Now we have what we want. A single number gives us the radius of the can of soda, which makes it have a minimum surface so that it contains the required volume. We use the function N from SymPy which evaluates an expression. Then, in line 20, we evaluate each candidate solution and create a new list with the numbers instead of the expressions.

Note: An interesting fact is that soda cans don’t have the surface area that our optimization finds. They have a larger surface. So, it seems that soda companies aren’t too interested in minimizing the surface but in optimizing another thing. What that thing is? Who knows!

Exercise 2: Slopes and optimization

This could be a typical math exercise in a standard calculus course, but in this course, it’s a super-fun Python programming challenge.

Let’s make it more interesting and add the requirement of solving all three functions in a single Python script. You can try it first and then come back to check your answer.

The script would look like this:

Press + to interact
from sympy import symbols, diff, Eq, solve, pi, N, sin, Abs
# Define symbols
x = symbols('x', real=True)
# Define functions and the point to evaluate the derivative at
function_points = [
(x**3 + 9*x**2 + 6*x + 1, 10),
(sin(x + pi), pi/2),
(Abs(x), 0)
]
# Calculate derivatives and keep the points
dfs = list(map(lambda fp: (diff(fp[0], x), fp[1]), function_points))
# Print evaluated derivatives
for df, point in dfs:
print(f"f'(x) = {df}. Evaluated at x = {point} is {df.subs(x, point)}")
# Solve derivatives
equations = list(map(lambda fp: Eq(fp[0], 0), dfs))
solutions = list(map(lambda eq: solve(eq, x), equations))
# Get the numeric result for each list of solutions
solutions = list([list(map(N, sols)) for sols in solutions])
# Determine if solutions are minima or maxima
sol_index = 0
for f, _ in function_points:
eps = 0.1 # small number
print(f"f(x) = {f}")
for solution in solutions[sol_index]: # for every candidate point
before = df.subs(x, solution - eps) # f'(x - eps)
after = df.subs(x, solution + eps) # f'(x + eps)
if before < 0 and after > 0: # if it goes from - to +
print(f"Solution {solution} is a minimum")
elif before > 0 and after < 0: # else if it goes from + to -
print(f"Solution {solution} is a maximum")
else: # otherwise it is not a minimum nor a maximum
print(f"Solution {solution} is neither a minimum nor a maximum")
sol_index += 1
print("===========================\n")

This would be the code. But wait, it doesn’t work! If we read the error carefully, we realize the problem is with the function x|x|. According to SymPy, the derivative of this function is sign(x)sign(x), which is equal to 11 when x>0x > 0, equal to 1-1 when x<0x < 0, and equal to 00 when x=0x = 0.

The problem is that, according to SymPy, there’s no algorithm to solve the equation sign(x)=0sign(x) = 0. It seems like a simple equation, from the definition we know sign(x)=0sign(x) = 0 if x=0x = 0. But we can only know it because we know what specific function we’re dealing with. A computer program needs to try general methods to solve equations and not specific ones that apply to only a small portion of cases outside the scope of general approaches.

But the problem is deeper. The real issue is that x|x| doesn’t have a derivative when x=0x = 0 ...