Exercise
Random Value Generation
Objective
Develop a Python project with a class RandomNumber that includes three static methods:
GetFloat: Returns a value between 0 and 1 using the formula:
seed = (seed * a + c) % m
result = abs(seed / m)
GetInt(max): Returns an integer between 0 and max, calculated as:
result = round(max * GetFloat())
GetInt(min, max): Returns an integer between min and max (implement this).
Initialize with:
m = 233280; a = 9301; c = 49297; seed = 1;
Program this in Python and test the methods.
Example Python Exercise
Show Python Code
class RandomNumber:
# Static variables for random number generation
m = 233280
a = 9301
c = 49297
seed = 1
@staticmethod
def GetFloat():
"""
Generates a floating point number between 0 and 1 using the formula:
seed = (seed * a + c) % m
result = abs(seed / m)
"""
# Update the seed using the linear congruential generator formula
RandomNumber.seed = (RandomNumber.seed * RandomNumber.a + RandomNumber.c) % RandomNumber.m
# Calculate the float value between 0 and 1
result = abs(RandomNumber.seed / RandomNumber.m)
return result
@staticmethod
def GetInt(max):
"""
Generates an integer between 0 and 'max' using the formula:
result = round(max * GetFloat())
"""
# Generate a float and scale it by the max value
return round(max * RandomNumber.GetFloat())
@staticmethod
def GetIntRange(min, max):
"""
Generates an integer between 'min' and 'max' using the formula:
result = round((max - min) * GetFloat()) + min
"""
# Generate a float value between 0 and (max - min)
return round((max - min) * RandomNumber.GetFloat()) + min
# Test the RandomNumber class and methods
if __name__ == "__main__":
print("Testing RandomNumber Class:")
# Test GetFloat
print("GetFloat():", RandomNumber.GetFloat())
# Test GetInt with a maximum value of 10
print("GetInt(10):", RandomNumber.GetInt(10))
# Test GetIntRange with a range of 5 to 15
print("GetIntRange(5, 15):", RandomNumber.GetIntRange(5, 15))
# Test with different ranges
print("GetIntRange(100, 200):", RandomNumber.GetIntRange(100, 200))
print("GetInt(50):", RandomNumber.GetInt(50))
Output
Testing RandomNumber Class:
GetFloat(): 0.11292986114866488
GetInt(10): 1
GetIntRange(5, 15): 8
GetIntRange(100, 200): 183
GetInt(50): 48
Share this Python Exercise