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

如何在纯Python中实现十进制数拆分为和为原值的随机数组

Pure Python Implementation to Split a Decimal into a Random Array with Sum Equal to Original Value

Got it, you can absolutely pull this off using just Python's standard libraries—no third-party packages needed. Here's a straightforward implementation that generates a random array where the sum of elements matches your original decimal number:

The Implementation Code

import random

def random_by_number(number, min_random, max_random, spaces=1, precision=2):
    # Handle edge case where we don't need to split the number
    if spaces <= 0:
        return number
    
    # Generate initial random numbers within the specified range
    random_numbers = [random.uniform(min_random, max_random) for _ in range(spaces)]
    
    # Calculate the adjustment needed to make the sum equal to the original number
    total_diff = number - sum(random_numbers)
    increment = total_diff / spaces
    
    # Adjust each random number and round to the desired precision
    return [round(num + increment, precision) for num in random_numbers]

# Example usage
if __name__ == "__main__":
    original_number = 2500.50
    split_count = 30
    
    # Set reasonable min/max bounds for each random element (60% to 100% of the average value)
    avg_value = original_number / split_count
    min_val = avg_value * 0.6
    max_val = avg_value
    
    result_array = random_by_number(original_number, min_val, max_val, spaces=split_count, precision=2)
    
    print("Generated random array:", result_array)
    print("Number of elements:", len(result_array))
    print("Sum of array elements:", sum(result_array))

How It Works

Let's break down the logic step by step:

  • First, we handle the edge case where we don't need to split the number (if spaces is 0 or negative, just return the original number).
  • We generate spaces random numbers using random.uniform(), which gives us values between the provided min_random and max_random.
  • We calculate how much the sum of these initial random numbers differs from the original value, then split that difference evenly across all elements as an increment.
  • Finally, we adjust each random number by the increment and round to the specified decimal precision to keep things clean.

Example Output

When you run the code, you'll get something like this (your random values will differ, of course):

Generated random array: [87.52, 85.11, 81.03, ..., 82.45]
Number of elements: 30
Sum of array elements: 2500.5

The sum will always match your original number, thanks to the adjustment step that distributes the difference evenly across all elements.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:50:22