How do I create a while loop with this percent error function that will work?
Mostrar comentarios más antiguos
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
2 comentarios
Chandrasekhar
el 10 de Mzo. de 2014
what do you want to find exactly?
Cameron
el 12 de Mzo. de 2014
Respuestas (1)
Mischa Kim
el 10 de Mzo. de 2014
Editada: Mischa Kim
el 12 de Mzo. de 2014
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 comentarios
Cameron
el 10 de Mzo. de 2014
Mischa Kim
el 12 de Mzo. de 2014
Updated code. Now also contains the percent error as the third column in the outdata array.
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!