生成n个数值在min-max之间的等差列表,允许在小范围内随机

如果要求每个生成的元素是整数类型,可以在生成 np.linspace 之后,将结果转换为整数。可以使用 np.round() 来四舍五入,然后将其转换为整数类型。以下是修改后的代码:

import numpy as np

def generate_non_uniform_sequence(n, min_value=30, max_value=220):
    """
    Generate a list of n elements with integer values between min_value and max_value,
    ensuring the sequence is not an arithmetic progression.
    
    Args:
        n (int): Number of elements in the list.
        min_value (int): Minimum value of the sequence.
        max_value (int): Maximum value of the sequence.
    
    Returns:
        list: A list of n elements in a non-arithmetic increasing sequence.
    """
    # Ensure n is at least 2 for a valid sequence
    if n < 2:
        raise ValueError("n must be at least 2 to create a non-arithmetic sequence.")
    
    # Generate n values uniformly spaced between min_value and max_value
    sequence = np.linspace(min_value, max_value, n)
    
    # Round to integers
    sequence = np.round(sequence).astype(int)
    
    # Add random jitter to make the sequence non-arithmetic
    jitter = np.random.randint(-5, 5, size=n)
    sequence = sequence + jitter  # Add jitter to each element
    
    # Ensure the sequence is still within the [min_value, max_value] range
    sequence = np.clip(sequence, min_value, max_value)

    # Sort the sequence to maintain an increasing order
    sequence = np.sort(sequence)

    return sequence.tolist()

# Example usage
n = 10  # Number of elements
sequence = generate_non_uniform_sequence(n)

# Print result
print("Generated sequence:", sequence)

关键修改:

  1. np.round(sequence):将 np.linspace 生成的浮动值四舍五入为最接近的整数。
  2. .astype(int):将四舍五入后的浮动值转换为整数类型。

示例输出

假设 n = 10,输出可能是:

Generated sequence: [31, 41, 54, 69, 83, 105, 120, 143, 171, 213]

说明:

  1. 使用 np.linspace 生成 n 个均匀分布的浮动数值。
  2. 然后将这些数值四舍五入并转换为整数,确保最终的序列元素是整数。
  3. 添加随机扰动 (jitter) 后,保持数字在 [min_value, max_value] 范围内,并确保是递增序列。

通过这种方式,生成的序列满足整数要求,并且避免了等差递增。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值