home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!ontek!mikey
- From: mikey@ontek.com (euphausia superba)
- Newsgroups: comp.lang.c
- Subject: Re: How can you evaluate an arbitrary function?
- Message-ID: <2213@ontek.com>
- Date: 8 Jan 93 21:43:47 GMT
- References: <1993Jan6.202453.8630@news.tufts.edu>
- Organization: Ontek Corporation -- Laguna Hills, California
- Lines: 72
-
- In comp.lang.c, slahiri@jade.tufts.edu (Sandip Lahiri) writes:
- | Suppose you have to write a program which would accept any arbitrary
- | function f(x) and calculate its values for x = ... . The program has
- | to be written in C. How would you go about it ? Note, common lisp
- | does have the eval primitive and this task is considerably easier
- | if the program is written in lisp. Should you write a parser first to
- | check the input ? Remember we can have a function nested to any
- | arbitrary depth e.g. f(x) = tan(tanx + sin(cos(sinx + x^2)) + 5).
-
- This is a bit cheeky, but if you'd be allowed to use LISP's eval, I see
- no reason why the following shouldn't be fair play.
-
- ---
- #include <stdio.h>
-
- #define PART1 "#include <stdio.h>\n#include <math.h>\n"
- #define PART2 "main(argc, argv) int argc; char * argv;\n"
- #define PART3 "{ double x, f();\n scanf(\"%lg\", &x);\n"
- #define PART4 " while(!feof(stdin)) {\n"
- #define PART5 " printf(\"f(%lg) = %lg\\n\",x,f(x));\n"
- #define PART6 " scanf(\"%lg\",&x);\n }\n}\n"
- #define PART7 "double f(x) double x; \n{ return ("
- #define PARTZ "); }"
-
- #define TEMP_SRC "tempXXtemp.c"
- #define TEMP_RUN "./tempXXtemp"
- #define CC_PATH "cc"
-
- #define FROM_X 0.00
- #define TO_X 2.05
- #define INC_X 0.10
-
- main()
- {
- char formula[1000];
- double i;
- int status;
- FILE * fs;
-
- printf("please type in a formula in terms of x:\n");
- gets(formula);
-
- fs = fopen(TEMP_SRC, "w");
- fwrite(PART1, 1, strlen(PART1), fs);
- fwrite(PART2, 1, strlen(PART2), fs);
- fwrite(PART3, 1, strlen(PART3), fs);
- fwrite(PART4, 1, strlen(PART4), fs);
- fwrite(PART5, 1, strlen(PART5), fs);
- fwrite(PART6, 1, strlen(PART6), fs);
- fwrite(PART7, 1, strlen(PART7), fs);
- fwrite(formula, 1, strlen(formula), fs);
- fwrite(PARTZ, 1, strlen(PARTZ), fs);
- fclose(fs);
-
- printf("compiling...\n");
- sprintf(formula, "%s %s -o %s -lm", CC_PATH, TEMP_SRC, TEMP_RUN);
- status = system(formula);
- if (status != 0) exit(1);
-
- fs = popen(TEMP_RUN, "w");
- printf("running...\n");
- for (i = FROM_X; i < TO_X; i += INC_X)
- {
- fprintf(fs, "%lg\n", i);
- }
- pclose(fs);
-
- unlink(TEMP_SRC);
- unlink(TEMP_RUN);
-
- return 0;
- }
-