Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Biggest Rational Fraction Within Some Bounds

I am trying to place currency trades that match an exact rate on a market that only accepts integral bid/offer amounts. I want to make the largest trade possible at a specific rate. This is a toy program, not a real trading bot, so I am using C#.

I need an algorithm that returns an answer in a reasonable amount of time even when the numerator and denominator can be large (100000+).

static bool CalcBiggestRationalFraction(float target_real, float epsilon, int numerator_max, int denominator_max, out int numerator, out int denominator)
{
    // target_real is the ratio we are tryig to achieve in our output fraction (numerator / denominator)
    // epsilon is the largest difference abs(target_real - (numerator / denominator)) we are willing to tolerate in the answer
    // numerator_max, denominator_max are the upper bounds on the numerator and the denominator in the answer
    //
    // in the case where there are multiple answers, we want to return the largest one
    //
    // in the case where an answer is found that is within epsilon, we return true and the answer.
    // in the case where an answer is not found that is within epsilon, we return false and the closest answer that we have found.
    //
    // ex: CalcBiggestRationalFraction(.5, .001, 4, 4, num, denom) returns (2/4) instead of (1/2).


}

I asked a previous question that is similar (http://stackoverflow.com/questions/4385580/finding-the-closest-integer-fraction-to-a-given-random-real) before I thought about what I was actually trying to accomplish and it turns out that I am trying to solve a different, but related problem.

like image 704
John Shedletsky Avatar asked Jan 21 '23 22:01

John Shedletsky


1 Answers

The canonical way to solve your problem is with continued fraction expansion. In particular, see this section.

like image 120
Alexandre C. Avatar answered Jan 23 '23 12:01

Alexandre C.