Here is the relevant part of the solution:
#include <stdlib.h> #include <stdio.h> #include <math.h> double fun( double x, double y) { return sin( x*x + y*y )/ (x*x + y*y) ; } int main(int argc, char *argv[]) { int r, nrows, c, ncols, j; int red, grn, blu; double x, y, z ; FILE *image; /* check the command line parameters */ if ( argc != 8 ) { printf("topoMap fileName.ppm nrows ncols xmin xmax ymin ymax\n"); return 0; } /* open the image file for writing in binary mode */ if ( (image = fopen( argv[1], "wb") ) == NULL ) { printf("file %s could not be created\n", argv[1]); return 0; } nrows = atoi( argv[2] ); ncols = atoi( argv[3] ); double xmin = atof( argv[4] ); double xmax = atof( argv[5] ); double ymin = atof( argv[6] ); double ymax = atof( argv[7] ); /* write out the PPM Header information */ fprintf( image, "P6 "); fprintf( image, "%d %d %d ", ncols, nrows, 255 ); /* find min and max value of z */ double minz = fun( xmin, ymin ); double maxz = fun( xmin, ymin ); for ( r=0; r<nrows; r++ ) for ( c=0; c<ncols; c++ ) { x = xmin + (xmax-xmin)*c/ncols; y = ymin + (ymax-ymin)*r/nrows; z = fun( x, y ); if ( z < minz ) minz = z; if ( z > maxz ) maxz = z; } /* write out the pixel data */ int height; for ( r=0; r<nrows; r++ ) for ( c=0; c<ncols; c++ ) { /* translate row and column into x and y */ x = xmin + (xmax-xmin)*c/ncols; y = ymin + (ymax-ymin)*(nrows-r)/nrows; /* get the value of the function */ z = fun( x, y ); /* translate the value into a level 0..255 */ height = (int)(255*(z-minz)/(maxz-minz)); red = height; grn = height; blu = height; /* mark the axes (which might not be in the selected range) */ if ( fabs(y) <= 1.0/nrows || fabs(x) <= 1.0/ncols ) { red = 0; grn = 0; blu = 150; } fputc( red, image ); fputc( grn, image ); fputc( blu, image ); } /* close the file */ fclose ( image ); return 1; }
Comments: To produce a more visual image of the function, fo more in the translation from the function value into color.