You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python数学函数优化及Float Division By Zero错误排查求助

Fixing "Float Division By Zero" Error in Scipy's minimize_scalar for Cost Function Optimization

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 set method='bounded' to lock the optimizer into positive n values. The lower bound 1e-6 avoids zero while still allowing very small positive numbers, and the upper bound 1e12 gives enough room for large values if needed.
  • Parameterized Cost Function: By nesting minimF inside function, we use the input parameters N, ca, cs, theta directly instead of hardcoding them. This makes your code reusable for different input values.
  • Cleaner Arithmetic: I simplified the calculation a bit (e.g., 0.5 instead of 1/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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 12:52:30