GMLscripts.com

Discuss and collaborate on GML scripts
Invert

You are not logged in.

#1 2009-06-22 20:05:15

XShortGuy
Member
Registered: 2009-06-20
Posts: 1

Decimal to Fraction Script

I have all ready submitted this script to the site, but I figure that I might as well post it here as well:
(Questions, Comments, and Improvements are welcome.)

/*
**  Usage:
**      convert_fraction(real number)
**
**  Argument:
**      Any real number
**
**  Returns
**      A string
**
*/
{
    var number, pow, mag, gcf, numer, denom;
    number = argument0;
    pow = string_length(string_digits(frac(number)))
    mag = power(10, pow)
    gcf = gcd(mag, number * mag)
    denom = mag / gcf;
    numer = number / gcf;
    return string(numer) + "/" + string(denom);
}

This relies on a gcd script, such as this one found on the site:

/*
**  Usage:
**      gcd(a,b)
**
**  Arguments:
**      a,b     non-negative integers
**
**  Returns:
**      the greatest common divisor of the given integers
**
**  GMLscripts.com
*/
{
    var a,b,r;
    a = max(argument0,argument1);
    b = min(argument0,argument1);
    while (b != 0) {
        r = a mod b;
        a = b;
        b = r;
    }
    return a;
}

Offline

#2 2009-06-26 05:34:54

Yourself
Member
Registered: 2007-10-09
Posts: 48

Re: Decimal to Fraction Script

pow = string_length(string_digits(frac(number)))

There's nothing in that line that turns number into a string.  It'd also probably be faster and more accurate to multiply by 2 (and by more accurate I mean the rational result will be exact insofar as the double data type is concerned).

Offline

Board footer

Powered by FluxBB