如何在纯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
spacesis 0 or negative, just return the original number). - We generate
spacesrandom numbers usingrandom.uniform(), which gives us values between the providedmin_randomandmax_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
相关产品推荐
相关产品推荐

