SymPy
directlyFirst we get the SymPy
object:
How can we minimise the amount of material used to produce a cylindric tin can that contains 1 litre. The cylinder has diameter d and height h. The question is therefore: What is d and h?
We introduce the variables d
(diameter) and
h
(height):
The problem is a constrained optimisation problem, and we solve it by
a Lagrange multiplier, and therefore we introduce lam
(the
Lagrange multiplier):
We now set up the problem:
area_str <- "Pi/2 * d**2 + Pi * h * d"
vol_str <- "Pi/4 * d**2 * h"
lap_str <- paste0("(", area_str, ") - lam*((", vol_str, ") - 1)")
lap <- sympy$parsing$sympy_parser$parse_expr(
lap_str,
local_dict = list('d' = d, 'h' = h, 'lam' = lam))
We can now find the gradient:
And find the critical points:
We take the one with the real solution:
We now have a short helper function to help getting appropriate
R
expressions (such a function will be included in later
versions of this package):
to_r <- function(x) {
x <- as.character(x)
x <- gsub("Pi", "pi", x, fixed = TRUE)
x <- gsub("**", "^", x, fixed = TRUE)
x <- parse(text = x)
return(x)
}
sol_d <- to_r(sol[[1]]$d)
sol_d
eval(sol_d)
sol_h <- to_r(sol[[1]]$h)
sol_h
eval(sol_h)
(It is left as an exercise to the reader to show that the critical point indeed is a minimum.)