How do you create a Taylor expansion to solve sinx for values of x in degrees?

7 views (last 30 days)
Please help me! I cant figure out how to solve this problem! I was able to convert x from degrees to radians, but I cant get my error tolerance to define or calculations of sin(x) for any x value.
The Taylor’s series expansion for sin x where x is in radians is:
sin(x) = summation of ((-1)^n)*x^(2*n+1)/factorial(2*n+1)
Write a Matlab script which calculates the sin of x by using the Taylor series expansion x specified in degrees. Calculate the sin of x using a while loop where the stopping criteria is the error E < 1x 10-6. E which is defined below is a function of the summation at the values of n (Sn) and n-1 (Sn-1).
E=abs((factorial(n)-factorial(n-1))/(factorial(n-1)))
As part of the problem your program should calculate the values of sin x at various values of x in degrees and tabulate using an fprintf statement as follows:
For x = 30:30:180 degrees, Calculate sin(x) and display both in a 2 column table
This is what I have so far. Does the code make sense?
clear
clc
%Problem 4 Hwk 1
%x degrees, must convert to radians first
n=25;
x=30:30:180;
x=angle_radians(x)
while E > 1*10^(-6)
for i = 0:n
y = ((-1)^i)*x^(2*i+1)/factorial(2*i+1);
end
sinx= summation(y)
Sn =sum(y)-y(n);
end
%fprintf('x(deg) | sin(x) \n', x, sinx)
%fprintf('x= %0.4f S= /n', n, sinx)
function x =angle_radians(x)
x=pi/180*x;
end
function E =stopValue(sinx,Sn)
E=abs(((sinx-Sn))/Sn);
sinx = sum(y);
Sn =sum(y)-y(n);
end
function sinx = summation(~)
y = ((-1)^i)*x^(2*i+1)/factorial(2*i+1);
sinx = factorial(y)
end
  3 Comments
madhan ravi
madhan ravi on 29 Jan 2019
Edited: madhan ravi on 29 Jan 2019
while E < 1E-6
% ^-—-—- change it
By the way have looked https://www.mathworks.com/help/symbolic/taylor.html ? Plus why do you create a custom function when there already exists a custom function deg2rad() ?
Dylan Huss
Dylan Huss on 29 Jan 2019
Thanks for the fix on the E value and the custom function deg2rad()! My main problem now is that E is an undefined variable. I dont know how to set it. I looked at the Taylor series help, and I got a function. But I have no idea if I used it right.
Here's the updated code
clear
clc
%Problem 4 Hwk 1
%x degrees, must convert to radians first
n=25;
x=30:30:180;
x=deg2rad(x)
while E < 1E-6
for i = 0:n
y(i)= ((-1)^i)*x^(2*i+1)/factorial(2*i+1);
sinx=Taylor(y)
Sn =sinx-y(n)
E=Error(n)
end
end
%fprintf('x(deg) | sin(x) \n', x, sinx)
%fprintf('x= %0.4f S= /n', n, sinx)
function E = Error(n)
Sn= sinx -y(n);
E=abs(((sinx-Sn))/Sn)
end
function sinx = Taylor(y)
y(i)= ((-1)^i)*x^(2*i+1)/factorial(2*i+1);
sinx = taylor(y,x)
end

Sign in to comment.

Answers (0)

Products


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!