write a script which will calculate the value of cos(x) (ask the user for the value of x and n) : ( ) ∑( ) = − − − = − + − = − n k k k k x x x x 1 2( 1) 1 2 4 2( 1)! in matlab
main.m
% ask user for the value of x and nx = input('Enter the value of x: ');
n = input('Enter the value of n: ');
% initialize variablescosine = 1;
factorial_term = 1;
% calculate the value of cosine with the given formulafor k = 1:n
factorial_term = factorial_term * (2*k-1) * 2*k;
% successive terms are alternately added and subtractedifmod(k, 2) == 0 cosine = cosine - ((x^(2*k))/factorial_term);
else cosine = cosine + ((x^(2*k))/factorial_term);
endend% display the final resultfprintf('The value of cosine of %f is %f\n', x, cosine);
583 chars
22 lines
Note: this code uses the formula provided in the question that calculates cos(x) with the value of n_terms.