#include #include #include double can(double x) { /* Returns Cantor function y=f(x) */ int t; /* ternery (base 3) expansion of x */ double z, y; for(t= 0, y= 0.0, z= 0.5; t!= 1 && x> 0 ; z/= 2) { x*= 3; x-= ( t= (int) floor(x) ); if(t> 0) y+= z; } return y; } double ican(double y) { /* Returns inverse Cantor function x=f^-1(y) */ int b; /* binary (base 2) expansion of y */ double z, x; for(b= 0, x= 0.0, z= 2.0/3.0; y> 0 ; z/= 3) { y*= 2; y-= ( b= (int) floor(y) ); if(b> 0) x+= z; } return x; } int main(int ac, char **av) { /* Usage: cantor */ double x, y, dx; int n, i, inv; n = (ac> 1) ? strtol(av[1],0,NULL) : 10; inv = (ac> 2) && (*av[2]=='i'); /* Inverse: cantor i */ dx = 1.0/n - 1e-9; /* Avoid dyadics & ternaries */ for(i=0; i<= n; ++i) { x = i*dx; y = (inv) ? ican(x) : can(x); printf("%7.5f %7.5f\n", x, y); } }