Sum digits after vpa(N,100) ?

Hi MatLab!
I've stumbled across a problem. I wish to take all the first hundred digits in the square root of 2 ---> sqrt(2) and sum them up.
I first use
N=sym('sqrt(2)'); vpa(N,100)
which gives me alot of digits. But when I try to num2str the answer it cant be done. How can I achieve this?

 Accepted Answer

Here you go:
clear all
digits(100);
N=vpa(sym('sqrt(2)'));
sumA = 0;
for i = 1:100
sumA = sumA + (floor(N*(10^(i-1))) - 10*floor(N*10^(i-2)));
end
disp(sumA)

More Answers (1)

Jan
Jan on 16 Jan 2013
Edited: Jan on 16 Jan 2013
Could you operate on the VPA number instead of converting it to a string? I do not have the Symbolic Toolbox, but I guess:
s = 0;
x = vpa(N, 100);
for ii = 1:100
s = s + floor(x);
x = rem(x, 1) * 10;
end
Does this work?
[EDITED]
N = sym('sqrt(2)');
x = vpa(N, 100);
s = 0;
for ii = 1:100
f = floor(x);
s = s + f;
x = (x - f) * 10;
end
If rounding error appear, try it with 200 digits in the VPA command. Please use this as inspiration - as I said already, I do not have the corresponding toolboxes.

5 Comments

Per
Per on 16 Jan 2013
No I dont think so, says it's an undifined function or method 'rem' for input arguments of type 'sym'.
Cant copy paste from Linux till Windows it seems, but my code is just as you wrote but starts first line with: N=sym('sqrt(2)')
Jan
Jan on 16 Jan 2013
Edited: Jan on 16 Jan 2013
Then at least floor worked? This would be fine, because rem() can be emulated using floor() .
Per
Per on 16 Jan 2013
I've written it like this and it yields the answer 465. The correct answer is 475. So the code seems to be working but I dont know where my 10 little digits went :O
Jan
Jan on 16 Jan 2013
Edited: Jan on 16 Jan 2013
Then let's debug your algorithm:
x = 1.414213562373095...
-> iteration starts
x = x*10-floor(x)*10
= 14.14213... - 1 * 10
= 4.14...;
s = s + 4;
Does the 1 not matter? And why do the loop stop at 99, when you need 100 elements?
Another test:
S = ['1.41421356237309504880168872420969807856967187537694807', ...
'3176679737990732478462107038850387534327641572735013846', ...
'230912297024924836055850737212644121497099935831'];
D = S - '0';
sum(D(3:102))
Jan
Jan on 16 Jan 2013
Now I can run Matlab again. The [EDITED] version works and gives the correct result.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!