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
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.
댓글 수: 0
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!