Whats wrong with my code? Taylor series Approx with error

조회 수: 12 (최근 30일)
Rachel Watts
Rachel Watts 2020년 3월 31일
답변: James Tursa 2020년 4월 1일
When I take out the error if statement, the code works just fine and displays all iterations. However, with the error statement in (line 7 of code) the m file runs but will not display any answers.
x = 0.9;
true = sin(x);
s = 0; %initialize sum
for n = 0:20
f = (((-1)^n)*x^((2*n)+1))/(factorial((2*n)+1)); %McLauren Series for sin function
s = s+f; %sum the start with the series
error = ((true-s)/true)*100; %Percent Error Formula
if error < 0.0001 ,break;end
fprintf('%f\t %f\t %f\t\n',true,s,error);
end

답변 (1개)

James Tursa
James Tursa 2020년 4월 1일
You probably just need an absolute value
error = abs((true-s)/true)*100; %Percent Error Formula
That being said, true and error are names of existing MATLAB functions. You should probably pick different names such as true_value and err.

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by