带x[1]+x[2]=1约束的最小值求解及自定义函数实现咨询
Got it, let's break this down step by step. Since you have the constraint x[1] + x[2] = 1, we can simplify this problem drastically by reducing it to a single-variable optimization instead of juggling two variables with a constraint. Here's how to approach both generating the grid of valid values and finding the minimum result:
First, since x[2] = 1 - x[1], we only need to generate x[1] values between 0.01 and 0.99 (because x[2] also has to stay within the 0.01-1 range). We’ll create a function that generates these values, computes your target function for each pair, and returns the minimum value along with the corresponding optimal x[1] and x[2].
# First, define your target function using the constraint (x2 = 1 - x1) target_func <- function(x1) { x2 <- 1 - x1 # Calculate the quadratic expression as you specified x1^2 * 0.05126875 + 2 * (x1 * x2 * -0.00809375) + x2^2 * 0.03376875 } # Function to generate values and find the minimum find_min_grid <- function(start = 0.01, end = 0.99, step = 0.01) { # Generate all valid x1 values x1_vals <- seq(from = start, to = end, by = step) # Calculate target function value for each x1 func_results <- sapply(x1_vals, target_func) # Find the index of the minimum value min_idx <- which.min(func_results) # Return a list with all useful info list( minimum_value = func_results[min_idx], optimal_x1 = x1_vals[min_idx], optimal_x2 = 1 - x1_vals[min_idx], all_x1_values = x1_vals, all_x2_values = 1 - x1_vals, all_function_values = func_results ) } # Example usage grid_result <- find_min_grid() cat("Minimum value from grid search:", grid_result$minimum_value, "\n") cat("Optimal x1:", grid_result$optimal_x1, ", Optimal x2:", grid_result$optimal_x2, "\n")
If you don’t need to generate every possible value and just want the precise minimum, R’s optimize() function (designed for single-variable functions) is far more efficient than grid search. Again, we use the constraint to turn this into a single-variable problem.
# Use optimize() to find the exact minimum within the valid range optim_result <- optimize(f = target_func, interval = c(0.01, 0.99)) cat("Exact minimum value:", optim_result$objective, "\n") cat("Optimal x1:", optim_result$minimum, ", Optimal x2:", 1 - optim_result$minimum, "\n")
Key Note:
Your original optim() call didn’t account for the x[1]+x[2]=1 constraint, so it would have found the unconstrained global minimum (which doesn’t satisfy your requirement). By substituting x[2] = 1 - x[1], we automatically enforce the constraint while simplifying the problem.
内容的提问来源于stack exchange,提问作者RIckHenr

