Skip to content

Instantly share code, notes, and snippets.

@drusepth
Created February 20, 2014 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drusepth/9107486 to your computer and use it in GitHub Desktop.
Save drusepth/9107486 to your computer and use it in GitHub Desktop.
## Author: Andrew Brown
## Created: 2014-02-11
## Estimates cos using a Maclaurin series
function void = cosapprox (xrad, acceptable_error)
# Get true cos(xrad) value for error analysis
true_value = cos(xrad);
# Estimate value with Maclaurin series
term_index = 1;
approx = 1;
tic
while true
true_error = abs(true_value - approx);
approx_error = abs(true_error / true_value);
if approx_error <= acceptable_error
break
end
approx += ((-1)^term_index)*(xrad^(2 * term_index) / factorial(2 * term_index));
term_index++;
end
toc
fprintf('cos(%f) approximated to be %f\n', xrad, approx)
fprintf('true error: %f\n', true_error)
fprintf('approximate error: %f\n', approx_error)
endfunction
@drusepth
Copy link
Author

octave:50> cosapprox(1.0471975512, 0.00005)
Elapsed time is 0.0010159 seconds.
cos(1.047198) approximated to be 0.500000
true error: 0.000000
approximate error: 0.000001

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment