Created
June 16, 2025 08:32
-
-
Save Hammer2900/351e037160fba0182ac0164f974ca275 to your computer and use it in GitHub Desktop.
Как превратить случайное вещественное число (обычно 0..1) в случайное целое число между a и b.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import random | |
from collections import Counter | |
def random_int_from_float(a, b, float_val=None): | |
""" | |
Превращает случайное вещественное число (0..1) в случайное целое число между a и b (включительно). | |
Args: | |
a (int): Нижняя граница диапазона. | |
b (int): Верхняя граница диапазона. | |
float_val (float, optional): Предопределенное вещественное число от 0.0 до <1.0. | |
Если None, генерируется новое случайное число. | |
Returns: | |
int: Случайное целое число в диапазоне [a, b]. | |
""" | |
if a > b: | |
a, b = b, a | |
if float_val is None: | |
float_val = random.random() | |
if not (0.0 <= float_val < 1.0): | |
raise ValueError('Вещественное число должно быть в диапазоне [0.0, 1.0)') | |
num_values = b - a + 1 | |
result = int(a + (float_val * num_values)) | |
return result | |
all_generated_numbers = [] | |
def generate_and_log(a, b, float_val=None, description=''): | |
number = random_int_from_float(a, b, float_val) | |
all_generated_numbers.append(number) | |
if description: | |
print(f'{description} -> {number}') | |
else: | |
print(number) | |
return number | |
for i in range(100): | |
generate_and_log(1, 100, description=f'Случайное {i+1} (10-20)') | |
print('\n--- Используем предопределенные float ---') | |
generate_and_log(5, 10, 0.0, description='float_val = 0.0, a=5, b=10') | |
generate_and_log(5, 10, 0.1, description='float_val = 0.1, a=5, b=10') | |
generate_and_log(5, 10, 0.49, description='float_val = 0.49, a=5, b=10') | |
generate_and_log(5, 10, 0.5, description='float_val = 0.5, a=5, b=10') | |
generate_and_log(5, 10, 0.99, description='float_val = 0.99, a=5, b=10') | |
generate_and_log(5, 10, 0.9999999999999999, description='float_val = 0.9999999999999999, a=5, b=10') | |
print('\n--- Диапазон из одного числа ---') | |
generate_and_log(7, 7, 0.5, description='float_val = 0.5, a=7, b=7') | |
print('\n--- Перепутанные границы ---') | |
generate_and_log(10, 5, 0.5, description='float_val = 0.5, a=10, b=5') | |
frequency_dict = Counter(all_generated_numbers) | |
print('\n--- Статистика повторений чисел ---') | |
print(len(dict(frequency_dict))) | |
print(json.dumps(dict(frequency_dict), indent=2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment