Python数学函数优化及Float Division By Zero错误排查求助
Hey there! Let's break down why you're hitting that frustrating "Float Division By Zero" error and get your optimization working smoothly.
Why the Error Pops Up
Your cost function minimF(n) includes the term 10 ** 9 / n — so if n ever equals 0 (or gets extremely close to it), Python will throw that division-by-zero error. The root issue is that minimize_scalar (using its default Brent method) doesn't know your n should be a positive value. It might explore values near or equal to 0 during its search for the minimum, triggering the error.
The Fix: Restrict the Search to Valid Values
Since n is almost certainly a positive number (I assume it represents something like production quantity or a count that can't be zero), we just need to tell minimize_scalar to only search in a positive range. Also, let's make your code more flexible by using the parameters from your function instead of hardcoding values.
Here's the revised, working code:
import math from scipy.optimize import minimize_scalar def function(N, ca, cs, theta): # Define the cost function inside to use the passed parameters directly def minimF(n): return (N / n) * ca + (0.5 * n * cs * theta) # Minimize only over positive values of n (avoid zero entirely) C0_Min = minimize_scalar(minimF, bounds=(1e-6, 1e12), method='bounded') print(C0_Min) # Call the function with your original input values function(10**9, 9*10**6, 1/25, 180)
Key Changes Explained
- Bounded Search: We added
bounds=(1e-6, 1e12)and setmethod='bounded'to lock the optimizer into positivenvalues. The lower bound1e-6avoids zero while still allowing very small positive numbers, and the upper bound1e12gives enough room for large values if needed. - Parameterized Cost Function: By nesting
minimFinsidefunction, we use the input parametersN, ca, cs, thetadirectly instead of hardcoding them. This makes your code reusable for different input values. - Cleaner Arithmetic: I simplified the calculation a bit (e.g.,
0.5instead of1/2) for readability — the math is exactly the same, just easier to follow.
When you run this revised code, it should successfully find the minimum of your cost function without hitting the division-by-zero error.
内容的提问来源于stack exchange,提问作者Andrei Rus

