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

如何用Sympy生成可控制零系数占比的随机次数多项式?

使用Sympy生成带可控零系数占比的随机多项式

你可以通过自定义函数实现需求,结合Sympy的多项式构造能力和Python的随机模块,就能灵活控制次数、系数范围以及零系数的占比,类似randMatrix的逻辑:

实现代码

import sympy as sp
import random

def random_poly(min_degree=2, max_degree=10, coeff_min=-10, coeff_max=10, zero_prob=0.3):
    x = sp.symbols('x')
    # 随机选取多项式次数
    degree = random.randint(min_degree, max_degree)
    coeffs = []
    
    for _ in range(degree + 1):
        # 根据设定概率决定是否生成零系数
        if random.random() < zero_prob:
            coeffs.append(0)
        else:
            # 生成指定范围内的整数系数,可替换为有理数/浮点数
            coeffs.append(random.randint(coeff_min, coeff_max))
    
    # 确保最高次项系数不为0(避免实际次数低于选定值)
    while coeffs[-1] == 0:
        coeffs[-1] = random.randint(coeff_min, coeff_max)
    
    # 构造多项式并返回Poly对象
    poly_expr = sum(c * x**i for i, c in enumerate(coeffs))
    return sp.Poly(poly_expr, x)

参数说明

  • min_degree/max_degree: 多项式次数的随机范围(闭区间)
  • coeff_min/coeff_max: 非零系数的取值范围(整数)
  • zero_prob: 单个系数为0的概率(取值0-1,比如0.3代表30%的系数为0)

使用示例

# 生成次数3-8、系数-20到20、40%零系数的多项式
my_poly = random_poly(min_degree=3, max_degree=8, coeff_min=-20, coeff_max=20, zero_prob=0.4)

# 打印Poly对象
print(my_poly)
# 输出示例:Poly(-17*x**7 + 0*x**6 + 12*x**5 + 0*x**4 + 0*x**3 + 5*x**2 + 0*x - 19, x, domain='ZZ')

# 转换成可读的表达式形式
print(my_poly.as_expr())
# 输出示例:-17*x**7 + 12*x**5 + 5*x**2 - 19

扩展:使用有理数/浮点数系数

如果需要非整数系数,只需替换生成系数的逻辑,比如改成有理数:

# 替换原系数生成行
coeffs.append(sp.Rational(random.uniform(coeff_min, coeff_max)))

这样生成的系数会以分数形式呈现,避免浮点数精度问题。

内容的提问来源于stack exchange,提问作者MetalMathician

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 19:22:17