How can I add numbers to an array within a for loop so that I can graph them as values?
4 次查看(过去 30 天)
显示 更早的评论
So my goal with this code is to use Liebniz's approximation to approximate pi in 100-1000 iterations (depends on user input), and then calculate the erro % every step. The algorithm that sums up from 0 to N works fine along with the error equation. However, I'm having trouble with the second part of my code which is trying to plot the errors each step and I'm not sure how to do that. I attempted to do it with this code, but it doesn't graph anything and I'm guessing it's because the error variable is constantly overwritten each step:
disp("Computing Pi!");
N = input("Enter an integer N. This program will approximate pi given N iterations:");
disp("Liebniz Method:");
x=0;
t=linspace(0,1,101);
for k = 0:N
x = x + (1/((4*k+3)*(4*k+1)));
Liebniz = 8*x;
error = (abs(Liebniz-pi)/pi)*100;
end
disp(Liebniz);
plot(t, error);
Any suggestions on how to approach this? I'm relatively new to MATLAB.
0 个评论
回答(1 个)
Rene Riha
2020-2-7
Write error(k+1)=(abs(Liebniz-pi)/pi)*100; in the loop. That will save error values to the vector. Then write for exmaple plot(0:length(error)-1,error) for graph.
0 个评论
另请参阅
类别
在 Help Center 和 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!