/* * Speed Fraction * by: Charlton Harrison * Computes the best approximate fractions for a decimal */ #include #include #include #include /* for kbhit() */ #include #include /* Function for kbhit() - the gcc way */ /* Only works for the key though... */ int kbhit() { struct timeval wait; int ret; fd_set readfd; FD_ZERO(&readfd); FD_SET(0, &readfd); wait.tv_sec = 0; /* Wait zero seconds */ wait.tv_usec = 0; ret = select(1, &readfd, NULL, NULL, &wait); return(ret); } void main(int argc, char *argv[]) { int kcount=0; double x, h, m=0.5, lastp=0.0, p=0.0; long last10, lpa=0, lasta=0, a=0, lastb=0, b=0, e, t=0, c=1; /* Initializations */ if (argc != 2) { printf("Usage: spfrcn [decimal]\n"); exit(1); } printf("\nHit return at any time to stop...\n"); x = atof(argv[1]); printf("Ok: %.16f\n", x); while (1) { /* Main Loop */ t++; m+=x; e=m; h=((double)e / (double)t); if (fabs(h-x) < fabs(p-x)) { p=h; a=e; b=t; } if (a != lpa) { if (h==x) { printf("%ld / %ld : %.16f\n", a, b, p); exit(1); } last10 = pow(10, ((int)log10(e))); if ((int)(e/last10) != (int)(a/last10)) { printf("%ld / %ld : %.16f\n", a, b, p); lpa=a; } } kcount++; if (kcount==1000) { /* every 1000 loops check to see if kbhit */ kcount=0; if (kbhit()) { exit(1); } } } /* End of Main Loop */ }