generate a random nearest number for input in python

To generate a random number which is nearest to a given input number, you can use the random.uniform() function to generate a random float between two given boundaries. Then, you can use the math.floor() and math.ceil() functions to find the nearest integer smaller or greater than the generated float.

Here is an example code block:

main.py
import random
import math

input_num = 10.7
lower_bound = math.floor(input_num)
upper_bound = math.ceil(input_num)

random_num = random.uniform(lower_bound, upper_bound)

print(random_num)
189 chars
11 lines

In this example, input_num is the number for which we want to generate a nearest random number. We use math.floor() and math.ceil() to get the lower and upper boundaries around this number, i.e. 10 and 11 in this case. Then, we use random.uniform() to generate a float between these boundaries. Finally, the print() function is used to display the random number generated.

gistlibby LogSnag