CodeCodeCode

ENGR132: HW05 - e_stimate_name

May 1st, 2012
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.38 KB | None | 0 0
  1. function [] = e_estimate_name(input_val, input_accuracy)
  2.  
  3. % FUNCTION: Calculates the Tylor series to find e^(user's value)
  4. % within the given level of accuracy.
  5. %
  6. % INPUTS:
  7. % 1) input_val: The user's value.
  8. % 2) input_accuracy: The user's necessary accuracy.
  9. %  
  10. % OUTPUTS:
  11. % Will print: exp(user's value) = (calculated value)
  12.  
  13. %Sets the Tylor series n to 0.
  14. counter = 0;
  15. %Sets the current value to 0.
  16. val_cur = 0;
  17. %Sets the current sum of values to 0.
  18. val_sum = 0;
  19. %Sets the calculated level of accuracy to 1 in order to enter the loop.
  20. mat_accuracy = 1;
  21.  
  22. %Loops until the level of accuracy reached by the calculation is greater
  23. %than the user's necessary accuracy.
  24. while mat_accuracy > input_accuracy
  25.     %Sets current value to the Tylor series calculation where counter = n.
  26.     val_cur = input_val^counter / factorial(counter);
  27.     %Sets the sum to the previous sum plus the current value.
  28.     val_sum = val_sum + val_cur;
  29.     %Calculates accuracy by |e^(user input) - (sum)|
  30.     mat_accuracy = abs(exp(input_val) - val_sum);
  31.     %Increments counter (n) by 1.
  32.     counter = counter + 1;
  33. end
  34.  
  35. %Prints the user's value and the calculated value.
  36. fprintf('exp(%0.5f) = %0.5f\n', input_val, val_sum);
  37.  
  38. % e_estimate_name(2,0.001)
  39. % exp(2.00000) = 7.38871
  40. % e_estimate_name(-4,0.0001)
  41. % exp(-4.00000) = 0.01836
  42. % e_estimate_name(12.3,0.00005)
  43. % exp(12.30000) = 219695.98865
Advertisement
Add Comment
Please, Sign In to add comment