Jump to content

Float 2 Fraction


Quistess Alpha
 Share

You are about to reply to a thread that has been inactive for 1065 days.

Please take a moment to consider if this thread is worth bumping.

Recommended Posts

Thought I'd drop this here in case anyone else might need it in the future, it's a rather nice algorithm based on Stern-Brocot trees

vector float2frac(float f)
{   f=llFabs(f);
    vector l = <0,1,0>;
    vector r = <1,0,0>;
    vector m = <1,1,0>;
    vector ret = m;
    float diff=1000000000; // arbitrarily large number.
    while(diff>0.00001) // can tune accuracy.
    {   float val = m.x/m.y;
        float ndif;
        if(f>val)
        {   l=m;
            m+=r;
            ndif = f-val;
        }else if(f<val)
        {   r=m;
            m+=l;
            ndif = val-f;
        }else
        {   //llOwnerSay("Debug: exact!");
            return m;
        }
        if(ndif<diff)
        {   diff=ndif;
            ret = m;
        }
    }
    return ret;
}
default
{
    touch_start(integer total_number)
    {
        llOwnerSay((string)float2frac((1.0/2) / (1- (5.0/12)*(1.0/6) - (1.0/12)*(1.0/3) - (5.0/12)*(1.0/3)*(1.0/3) )));
    }
}

float2frac((float)a/b) == <a,b,0>;

should be true for almost all integer values of a and b, assuming rounding error doesn't get too bad.

Note: This will be /very/ inefficient for large floats (say, >20.0). float2frac is best used on floats between 0 and 1, that are not too close (0.999 0.001) to either.

Edited by Quistessa
clarification of scope.
  • Like 1
  • Thanks 2
Link to comment
Share on other sites

You are about to reply to a thread that has been inactive for 1065 days.

Please take a moment to consider if this thread is worth bumping.

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
 Share

×
×
  • Create New...