How to compute Pi using the Leibniz series sum((-1)^k / (2k+1)) = Pi/4 in MATLAB without using slow for loops?
Prashant Kumar answered .
2026-07-23
The Leibniz series approximates π using alternating fractions. In MATLAB, you can vectorize this computation for high execution speed:
% Vectorized Leibniz Series in MATLAB
N = 1000000; % Number of terms
k = 0:N;
terms = ((-1).^k) ./ (2*k + 1);
pi_approx = 4 * sum(terms);
fprintf('Approximated Pi after %d terms: %.8f\n', N, pi_approx);
fprintf('Error: %.8e\n', abs(pi-pi_approx));