Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // apple xcode
- // paulogp
- /* sine */
- /* computes sine using very simple floating arithmetic. */
- #include <stdio.h>
- #include <math.h>
- #include <stdio.h>
- static char *float_2_ascii (float the_num);
- float fix_float (float the_num);
- float factorial (float the_num);
- static char *float_2_ascii (float the_num)
- {
- static char the_result[15]; // place to put the number
- sprintf(the_result, "%8.3E", the_num);
- return (the_result);
- }
- float fix_float (float the_num)
- {
- float the_result; // result of the conversion
- char the_ascii[15]; // ascii version of number
- sprintf(the_ascii, "%8.4e", the_num);
- sscanf(the_ascii, "%e", &the_result);
- return (the_result);
- }
- float factorial (float the_num)
- {
- if (the_num <= 1.0)
- {
- return (the_num);
- }
- else
- {
- return (the_num *factorial(the_num - 1.0));
- }
- }
- int main (int argc, const char * argv[])
- {
- float the_test_value = 1.4;
- float the_total; // total of series so far
- float new_total; // newer version of total
- float term_top; // top part of term
- float term_bottom; // bottom of current term
- float the_term; // current term
- float the_exp; // exponent of current term
- float the_sign; // +1 or -1 (changes on each term)
- float the_value; // value of the argument to sin
- int the_index; // index for countin terms
- printf("calculating...\n\n");
- the_value = fix_float(the_test_value);
- the_total = 0.0;
- the_exp = 1.0;
- the_sign = 1.0;
- for (the_index = 0;; ++the_index)
- {
- term_top = fix_float(pow(the_value, the_exp));
- term_bottom = fix_float(factorial(the_exp));
- the_term = fix_float(term_top / term_bottom);
- printf("x++%d %s\n", (int)exp, float_2_ascii(term_top));
- printf("%d! %s\n", (int)exp, float_2_ascii(term_bottom));
- printf("x**%d/%d! %s\n", (int)exp, (int)exp, float_2_ascii(the_term));
- printf("\n");
- new_total = fix_float(the_total + the_sign * the_term);
- if (new_total == the_total)
- {
- break;
- }
- the_total = new_total;
- the_sign = -the_sign;
- the_exp = the_exp + 2.0;
- printf(" total = %s\n", float_2_ascii(the_total));
- printf("\n");
- }
- printf("%d term computed\n", the_index + 1);
- printf("rad sin(%s) = %s\n", float_2_ascii(the_value), float_2_ascii(the_total));
- printf("Actual sin(%G) = %G\n", the_test_value, sin(the_test_value));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement