我想该脚本输出159个随机数之间的“0.04”和“4.5”,有一个总匹配的目标总数。这是我到目前为止,但这只产生142个数字。我如何强制它创建159个数字?
import random
target_total = 298.51
total_numbers = 159
min_value = 0.04
max_value = 4.50
random_numbers = []
for i in range(total_numbers - 1):
# Generate a random number within the specified range
num = round(random.uniform(min_value, max_value), 2) # Limit to 2 decimal places
# Append the number to the list
random_numbers.append(num)
# Calculate the current sum of numbers
current_sum = round(sum(random_numbers), 2)
# If the current sum exceeds the target total, remove the last number
while current_sum > target_total:
excess = current_sum - target_total
random_numbers.remove(random_numbers[-1])
current_sum = round(current_sum - excess, 2)
# The last number is adjusted to reach the target total
last_num = round(target_total - sum(random_numbers), 2)
random_numbers.append(last_num)
# Print each generated number with row numbers on a new line
for i, num in enumerate(random_numbers, start=1):
print(f"Row {i}: {num}")
print("Total sum:", round(sum(random_numbers), 2))
字符串
1条答案
按热度按时间jv4diomz1#
问题在于:虽然max_value是4.50,但如果创建的随机数的数量接近最大值,为了达到目标总数,将使用较少的总数。此外,如果我们使用这种方法,循环将继续无限的数字。所以我们必须自己决定max_value。这里我给出了一个更好的方法。并在里面给出解释:
字符串
如果你想让每个随机数都是唯一的,你可以在第18行之后添加一个while循环。也就是说,我已经包含了你应该插入以下代码的那一行
型