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.
from sympy import symbols, diff, Eq, solve, pi# Define symbolsx = symbols('x', real=True)# Define functionf = 710/x + 2*pi*x**2# Calculate derivativedf = diff(f, x) # derivative of f with respect to x# Print derivativeprint(f"Derivative: {df}")# Solve derivativeequation = Eq(df, 0) # equation is df = 0solutions = solve(equation, x) # solve equation for xprint(f"Solutions: {solutions}")# Determine if solutions are minima or maximaeps = 0.1 # small numberfor solution in solutions: # for every candidate pointbefore = 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 maximumprint(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.
from sympy import symbols, diff, Eq, solve, pi, N# Define symbolsx = symbols('x', real=True)# Define functionf = 710/x + 2*pi*x**2# Calculate derivativedf = diff(f, x) # derivative of f with respect to x# Print derivativeprint(f"Derivative: {df}")# Solve derivativeequation = Eq(df, 0) # equation is df = 0solutions = solve(equation, x) # solve equation for x# Get the numeric resultsolutions = list(map(N, solutions))print(f"Solutions: {solutions}")# Determine if solutions are minima or maximaeps = 0.1 # small numberfor solution in solutions: # for every candidate pointbefore = 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 maximumprint(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:
from sympy import symbols, diff, Eq, solve, pi, N, sin, Abs# Define symbolsx = symbols('x', real=True)# Define functions and the point to evaluate the derivative atfunction_points = [(x**3 + 9*x**2 + 6*x + 1, 10),(sin(x + pi), pi/2),(Abs(x), 0)]# Calculate derivatives and keep the pointsdfs = list(map(lambda fp: (diff(fp[0], x), fp[1]), function_points))# Print evaluated derivativesfor df, point in dfs:print(f"f'(x) = {df}. Evaluated at x = {point} is {df.subs(x, point)}")# Solve derivativesequations = 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 solutionssolutions = list([list(map(N, sols)) for sols in solutions])# Determine if solutions are minima or maximasol_index = 0for f, _ in function_points:eps = 0.1 # small numberprint(f"f(x) = {f}")for solution in solutions[sol_index]: # for every candidate pointbefore = 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 maximumprint(f"Solution {solution} is neither a minimum nor a maximum")sol_index += 1print("===========================\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 . According to SymPy, the derivative of this function is , which is equal to when , equal to when , and equal to when .
The problem is that, according to SymPy, there’s no algorithm to solve the equation . It seems like a simple equation, from the definition we know if . 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 doesn’t have a derivative when ...