In my project, I built my own Fraction:
public partial struct Fraction
{
public double Numerator;
public double Denominator;
public readonly decimal Quotient
{
get
{
decimal quotient;
try
{
quotient = (decimal)Numerator / (decimal)Denominator;
}
catch
{
quotient = (decimal)(Numerator / Denominator);
}
return quotient;
}
}
}
I want to create a function that takes in a range and return a random Fraction within that range:
public static Fraction GenerateRandomFraction(Fraction Min, Fraction Max)
{
}
I tried to think about it but couldn't find an algorithm can achieve what I want. I tried to search online but couldn't find any All I found was about decimal. I can make it work using a workaround:
- Get the Quotient of the range.
- Generate a random decimal number.
- Convert it back to Fraction.
But I don't want to use it unless I'm 100% that's such algorithm doesn't exist.
Example: Min = 0/1, Max = 1/1 Result: 1/10 or 1/9, or 1/3 But I want it to be randomized.
If you are ok with limiting yourself to three digits each for the Numerator and Denominator the problem becomes fairly simple.
Start by creating all possible fractions and put them in a list. Then sort the list, you will need to implement comparison for your fractions to make this work. Then find the indices for your min and max fractions (or possibly the next lower/higher fraction) using BinarySearch. You can then simply generate a random integer between these indices and use this to find your fraction.
Note that there are infinite fractions between two fractions, and computers do not deal particular well with infinities. So if you cannot just list all the numbers to select from you may need to consider what the goal is. Nice looking numbers? Even sampling? speed? There will be tradeoffs depending on what you want to accomplish.