Compare digits of 2 strings
Show older comments
Looking to compare a string of pi to a calculated string to check for digit similarity between the two (ie 3.1415 compared to 3.1426, 3 digits accurate)
The idea is to put it into a table that can be read as 3 columns with "n values", "calculated values", "digit accuracy".
my issue is i dont know how to look at each character of the strings to compare, as when i try to get the 1st digit it responds with the whole string.
Example code:
clear; format longg;
calcPi=zeros(1, 4); digitAccuracy=zeros(1,4);
nrange=[1*10^2, 1*10^4, 1*10^6]; step=1;
piString=sprintf("%.14f", pi);%convert pi to a string with 14 decimals
for n=nrange
k=1:n;
sumEQ=sum(1./k.^2); %find (pi^2)/6
calcPi(step)=sqrt(6*(sumEQ)); %solve for pi
calcString=sprintf("%.14f",calcPi(step));%convert calcPi to string with 14 decimals
for i = 1:strlength(calcString) %loop for every digit of calcString
calcDigit=str2double(calcString(i)); %take i'th digit of calcString
piDigit=str2double(piString(i)); %take i'th digit of piString
if calcDigit == piDigit %are both i'th digits equal?
digitAccuracy(step) = 1+digitAccuracy(step); %if yes, increase counter by 1
end
end
step=step+1; %step increase for array indexing
end
Accepted Answer
More Answers (0)
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!