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 nx = input('Enter the value of x: ');
n = input('Enter the number of terms to include in the series: ');
% Initialize the result and the sign variableresult = 1;
sign = -1;
% Calculate the value of cos(x) using the taylor series expansionfori=2:2:n
term = (x^i)/factorial(i);
result = result + (sign*term);
sign = sign*-1;
end% Display the resultdisp(['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.5Enter the number of terms to include in the series: 5The value of cos(0.5) calculated using 5 terms in the series is 0.87758.