Guest User

Untitled

a guest
Aug 20th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. // apple xcode
  2. // paulogp
  3. // computes sine using very simple floating arithmetic
  4. #include <stdio.h>
  5. #include <math.h>
  6. #include <stdio.h>
  7.  
  8. static char *float_2_ascii (float the_num);
  9. float fix_float (float the_num);
  10. float factorial (float the_num);
  11.  
  12. static char *float_2_ascii (float the_num)
  13. {
  14. static char the_result[15]; // place to put the number
  15.  
  16. sprintf(the_result, "%8.3E", the_num);
  17.  
  18. return (the_result);
  19. }
  20.  
  21. float fix_float (float the_num)
  22. {
  23. float the_result; // result of the conversion
  24. char the_ascii[15]; // ascii version of number
  25.  
  26. sprintf(the_ascii, "%8.4e", the_num);
  27. sscanf(the_ascii, "%e", &the_result);
  28.  
  29. return (the_result);
  30. }
  31.  
  32. float factorial (float the_num)
  33. {
  34. if (the_num <= 1.0)
  35. return (the_num);
  36. else
  37. return (the_num *factorial(the_num - 1.0));
  38. }
  39.  
  40. int main (int argc, const char * argv[])
  41. {
  42. float the_test_value = 1.4;
  43.  
  44. float the_total; // total of series so far
  45. float new_total; // newer version of total
  46. float term_top; // top part of term
  47. float term_bottom; // bottom of current term
  48. float the_term; // current term
  49. float the_exp; // exponent of current term
  50. float the_sign; // +1 or -1 (changes on each term)
  51. float the_value; // value of the argument to sin
  52. int the_index; // index for countin terms
  53.  
  54. printf("calculating...\n\n");
  55.  
  56. the_value = fix_float(the_test_value);
  57.  
  58. the_total = 0.0;
  59. the_exp = 1.0;
  60. the_sign = 1.0;
  61.  
  62. for (the_index = 0;; ++the_index)
  63. {
  64. term_top = fix_float(pow(the_value, the_exp));
  65. term_bottom = fix_float(factorial(the_exp));
  66. the_term = fix_float(term_top / term_bottom);
  67.  
  68. printf("x++%d %s\n", (int)exp, float_2_ascii(term_top));
  69. printf("%d! %s\n", (int)exp, float_2_ascii(term_bottom));
  70. printf("x**%d/%d! %s\n", (int)exp, (int)exp, float_2_ascii(the_term));
  71. printf("\n");
  72.  
  73. new_total = fix_float(the_total + the_sign * the_term);
  74.  
  75. if (new_total == the_total)
  76. break;
  77.  
  78. the_total = new_total;
  79. the_sign = -the_sign;
  80. the_exp = the_exp + 2.0;
  81.  
  82. printf(" total = %s\n", float_2_ascii(the_total));
  83. printf("\n");
  84. }
  85.  
  86. printf("%d term computed\n", the_index + 1);
  87. printf("rad sin(%s) = %s\n", float_2_ascii(the_value), float_2_ascii(the_total));
  88. printf("Actual sin(%G) = %G\n", the_test_value, sin(the_test_value));
  89.  
  90. return 0;
  91. }
Add Comment
Please, Sign In to add comment