How do I create a while loop with this percent error function that will work?
이전 댓글 표시
Consider the following infinite series: f(x)=2[ x+ x^3/3+ …….+ x^(2n-1)/(2n-1 )+ …… ]
This series represents the function: f(x)=ln〖( (1+x)/(1-x)〗 ) for -1 < x < +1
Implement this formula to evaluate the function from x=-0.95 to x=+0.95 with increments of 0.05. For each value of x, use just enough number of terms in the series such that the %error defined below is less than or equal to 1x10-5.
%error=abs( (true value-series approximation)/(true value) )×100
This is what I have so far, I just don't know how to get the function to run for multiple values and record those values: function [nt appr perr] = series(x,nterms) true = log((1+x)/(1-x)); sumx = 0; for n =1:nterms; nt(n) = n; sumx = sumx+(2*((x^(2*n-1))/(2*n-1))); appr(n) = sumx; perr(n) = abs((true-appr(n))/true)*100; end zz=[nt;appr;perr]; fprintf('No.terms app.value percent err\n'); fprintf('%7d %13.6f %12.6f\n',zz); end
답변 (1개)
Mischa Kim
2014년 3월 10일
편집: Mischa Kim
2014년 3월 12일
Cameron, there are a couple of thing:
function outdata = my_series(xlim, dx, err)
x = xlim(1):dx:xlim(2);
outdata = zeros(length(x),4);
for ii = 1:length(x)
appr = 0;
true = log((1 + x(ii))/(1 - x(ii)));
jj = 1;
while abs(100*(true - appr)/true)>err
appr = appr + 2*x(ii)^(2*jj-1)/(2*jj-1);
jj = jj + 1;
end
outdata(ii,:) = [true appr 100*(true-appr)/true jj];
end
% fprintf('No.terms app.value percent err\n');
% fprintf('%7d %13.6f %12.6f\n',zz); end
- series is a built-in function, use another function name.
- Use two loops: one that steps through all your x-values, the second that finds the approximation for each x-value.
- You could print your results. It's a little cleaner to return results as output of your function first. If you call the function using
outdata = my_series([-0.5 0.5], 0.05, 1e-5)
and without semi-colon at the end of the command, the array will be printed anyways.
댓글 수: 2
Cameron
2014년 3월 10일
Mischa Kim
2014년 3월 12일
Updated code. Now also contains the percent error as the third column in the outdata array.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!