write a script for cos(x) taylor series with inputs for x and n in matlab

main.m
% This script calculates the value of cos(x) using the taylor series expansion.
% The user is prompted to enter the value of x and the number of terms to include in the series.
% Define the inputs - x and n
x = input('Enter the value of x: ');
n = input('Enter the number of terms to include in the series: ');

% Initialize the result and the sign variable
result = 1; 
sign = -1;

% Calculate the value of cos(x) using the taylor series expansion
for i=2:2:n
    term = (x^i)/factorial(i);
    result = result + (sign*term);
    sign = sign*-1;
end

% Display the result
disp(['The value of cos(' num2str(x) ') calculated using ' num2str(n) ' terms in the series is ' num2str(result) '.']);
693 chars
20 lines

Example output:

main.m
Enter the value of x: 0.5
Enter the number of terms to include in the series: 5
The value of cos(0.5) calculated using 5 terms in the series is 0.87758.
153 chars
4 lines

gistlibby LogSnag