Finding self-locating loops in pi, receiving "Index exceeds the number of array elements. Index must not exceed 50."
1 view (last 30 days)
Show older comments
Hi, as per title I came into this error. Is this related to memory or perferences perhaps?
% Define the number of digits to use from pi
numDigits = 100000;
% Load the first numDigits digits of pi into a string
piStr = num2str(pi, numDigits);
% Loop over all possible loop lengths
for loopLen = 1:floor(numDigits/2)
% Loop over all possible starting positions for the loop
for startPos = 1:numDigits-loopLen*2
% Extract the loop and the following sequence from piStr
loopStr = piStr(startPos:startPos+loopLen-1);
seqStr = piStr(startPos+loopLen:startPos+loopLen*2-1);
% Check if the loop appears again in seqStr
if contains(seqStr, loopStr)
fprintf('Found self-locating loop of length %d\n', loopLen);
fprintf('Loop starts at position %d\n', startPos);
fprintf('Loop sequence: %s\n', loopStr);
fprintf('Following sequence: %s\n', seqStr);
end
end
end
2 Comments
Answers (1)
chicken vector
on 1 Jun 2023
Edited: chicken vector
on 1 Jun 2023
The error comes from the fact that 50 is the maximum number of digits for pi.
You can have a proof of this by doing:
nDigits = 60;
num2str(pi, nDigits)
num2str(pi, ['%.' num2str(nDigits) 'f'])
Note that double precision floating point numbers have 16 digit of accuracy.
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!