|
"Robert Collins" <rob.robandsue@btinternet.com> wrote in message
news:kqono4$cpm$1@newscl01ah.mathworks.com...
> I have noticed this too.
>
> The code below calculates the answer to Problem 162 on the Project Euler
> website in two slightly different ways but should give the same answer.
>
> sum1=0;
> sum2=0;
>
> for n=3:16
>
> f1=vpa(16^(n-1)-2*15^(n-1)+14^(n-1));
The way you've written this code, the quantity inside the VPA call is
computed IN DOUBLE PRECISION and then displayed to an arbitrary number of
decimal places.
http://www.mathworks.com/help/symbolic/vpa.html
"When you apply vpa to a numeric expression, such as 1/3, 2^(-5), or
sin(pi/4), it is evaluated to a double-precision number. Then, vpa is
applied to that double-precision number. For more accurate results, convert
numeric expressions to symbolic expressions. For example, to approximate
exp(1) use vpa(sym(exp(1))."
In particular, when n is 14:
>> n = 14;
>> y = 16^(n-1)-2*15^(n-1)+14^(n-1)
y =
1.40492426390589e+15
That's getting pretty close to FLINTMAX.
www.mathworks.com/help/matlab/ref/flintmax.html
If you want to perform computations in arbitrary precision, include a
symbolic variable or expression in your computation.
>> s = sym(16);
>> n = 14;
>> y1 = s^(n-1)-2*(s-1)^(n-1)+(s-2)^(n-1)
y1 =
1404924263905890
> f2=vpa(16^(n-1)-3*15^(n-1)+3*14^(n-1)-13^(n-1));
>> s = sym(16);
>> n = 14;
>> y2 = s^(n-1)-3*(s-1)^(n-1)+3*(s-2)^(n-1)-(s-3)^(n-1)
y2 =
743283635462550
> ans1=2*f1+13*f2;
>> 2*y1 + 13*y2
ans =
12472535788824930
> sum1=sum1+ans1;
>
> ans2=vpa(15*16^(n-1)-15^n-2*14*15^(n-1)+2*14^n+13*14^(n-1)-13^n);
> sum2=sum2+ans2;
>
> end
>
>
> Up to n=13 both routes give the same answers for ans1 and ans2. At n=14
> they diverge and produce different values. Setting the number of digits
> to 60 has no effect (the final sums have 19 digits).
>
> For n=14 vpa doesn't appear to add the two sub values F1 anf f2 properly
> either. For n=14, f1 and f2 are both calculated to end in 0 but vpa adds
> 2*f1 + 13*f2 to give a number ending in 6.
>
> The sums sum1 and sum2 for n=3:16 are wrong by both methods calculated
> above
--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com
|