function [terms, approx] = approx_sin(x , thereshold) terms = 0; real = sin(x);
ID: 3568726 • Letter: F
Question
function [terms, approx] = approx_sin(x , thereshold)
terms = 0;
real = sin(x);
y=0;
while abs((real - y)/ real) ~= thereshold
for i = 1:10
y=(-1)^(i+1) * x.^(2*i-1)/ factorial(2*i-1)
terms = terms + 1;
end
approx = y ;
end
disp(y)
disp(terms)
end
I am wondering where I am going wrong with my code.I am trying to approximate the sin of x in a function, but it keeps running in a infinite loop and I am not entirely sure what I am doing wrong. If anyone could point me in the right direction I would be very grateful. Iam using Matlab to perform this too, not java or other ones.
Explanation / Answer
You did not update y at each step. You need to do that. Also, I changed your while loop condition a bit. Have a look, the attached code works,
function [terms, approx] = approx_sin(x , thereshold)
terms = 0;
real = sin(x)
y=0;
while (abs((real - y)/ real) >= thereshold)
for i = 1:10
y=y+(-1)^(i+1) * x.^(2*i-1)/ factorial(2*i-1);
terms = terms + 1;
end
approx = y;
disp(y)
disp(terms)
end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.