Hi! I need to verify my code of this funtion! thanks

2 次查看(过去 30 天)
HI! I NEED HELP WITH THE FOLLOWING: Implement the equation in a function (pi/8)= 1/1*3+1/5*7+1/9*11.... that receives the relative error willing to accept and return the user a vector with all values of π estimated and other vector with relative errors associated with each value of π. The function is in arrays. I did my function, but there is something wrong:
function [ES,ER]=piecuacionpi8(x)
RT=pi;
ter=0;
estimado=1;
er=2*x;
ER = [] ;
ES = [];
a=0;
while er>=x
z=a+(1/((((2*ter)-1)^2)*(((2*ter)+1)^2)));
em=sqrt((a*16)+8);
estimado=(estimado*z);
es=estimado* 8;
er=100*abs((es-RT)/RT);
ter=ter+1;
ES(ter) = em ;
ER(ter) = er ;
end
return
Thanks a lot!

回答(2 个)

Jan
Jan 2016-11-1
Using meaningful names for the variables would decrease the confusion level: x, er, ER, em, z???
You want to build a sum collecting all terms. So "a = a + ..." sounds more reasonable than "z = a + ...".
The relation between "(pi/8)= 1/1*3+1/5*7+1/9*11...." and "(1/((((2*ter)-1)^2)*(((2*ter)+1)^2)))" is not obvious. I do not understand the purpose of
em=sqrt((a*16)+8);
estimado=(estimado*z);
es=estimado* 8;
also. Without seeing the connection between the code and the question, it is hard to guess, what's going wrong in your opinion. I suggest to start again with creating the sum of:
8 * (1/(1*3))
8 * (1/(1*3) + 1/(5*7))
etc.

Guillaume
Guillaume 2016-11-1
Jan is spot on with variable names. Use meaningful words, not abbreviations or one or two letter names. It makes it so much easier to follow the flow of the program. I mean, what's the point of renaming pi to RT? In what way does writing RT instead of pi helps?
I too find it hard to read your (1/((((2*ter)-1)^2)*(((2*ter)+1)^2))) expression. There are brackets there that are not necessary since operator precedence is well defined.
a + 1 / ((2*ter-1)^2 * (2*ter+1)^2)
is a lot more readable and produces the same result (assuming you didn't botch the brackets). It also makes it immediately obvious (at least to me) that you didn't implement the equation right.
Like Jan, I really don't understand what you're trying to do the next few lines. Where does the square root come from? Note that as implemented a stays 0 the whole time, so em is always sqrt(8) and you're always putting that in ES.
Anyway, I suggest you learn to use the debugger. Step through your code line by line. See what ends up in each variable and compare it to what you expect. You'll quickly find the many mistakes you've made.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by