foating point number to fraction

#include <stdio.h>

long gcd(long a, long b)
{
long t;
while(b)
{
t = b;
b = a % b;
a = t;
}
return a;
}

inline long lcm(long a, long b)
{
return abs(a * b) / gcd(a,b);
}

void d2f(double n)
{
if((n - (long) n) == 0.0) //if there is no digits after decimal
{
printf("%ld/1\n", (long)n);
return;
}

long de = 1;

n += 0.1; //to avoid round off errors for example .23, .28 etc..
while((n - (long) n) != 0.0)
{
n *= 10;
de *= 10;
}

long nu = n;

//substract 1/10
long l = lcm(de, 10);
nu = nu * (l / de) - l/10;

//simplify the fraction
long g = gcd(nu, l);

printf("%ld/%ld\n", nu/g, l/g);
}

int main()
{
double n;

scanf("%lf", &n);

d2f(n);
}

Advertisements

3 thoughts on “foating point number to fraction

  1. haah it fails at recurring fractions like 1.33 where it prints 133/100 rather than 4/3.So use formulaN is the no with decimal shifted to rightmost.frac=(N-non Recurring part)/(999…X10…)eg .423232323….=(423-4)/(99X10)

  2. I like the impressive idea based on elementary mathematics. But floating point numbers have peculiar properties. For example, the number 10.3838383838, the while loop will not run for completion. After we collect, 10383838383.8, the number turns into 10383838383.7999999999 :(.So the loop will run for ever.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s