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.py189 chars11 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