Filter löschen
Filter löschen

How can I add numbers to an array within a for loop so that I can graph them as values?

3 Ansichten (letzte 30 Tage)
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.

Antworten (1)

Rene Riha
Rene Riha am 7 Feb. 2020
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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by